Notification自定義界面
前言
之前在做一個手機的播放器,需要做到在通知欄顯示控制播放的界面,如下:

這是讓服務在前臺運行就可以實現(xiàn)的(可以參考我的前一篇文章Service在前臺運行),今天我們就要實現(xiàn)Notification的自定義界面,當然就不實現(xiàn)如上圖所示的了,而是下面一個簡單的界面,隨自己的需要搭建自己想要的界面。

可以看到,我實現(xiàn)了一個簡單的界面,包括一個ImageView和Button,下面我就說說該如何實現(xiàn)它,其實很簡單。
實現(xiàn)
首先我們要準備一個界面文件:
notification.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_marginTop="10dp" android:layout_marginBottom="10dp" android:background="#333300" android:layout_width="match_parent" android:layout_height="match_parent"> <ImageView android:paddingLeft="20dp" android:layout_width="70dp" android:layout_height="50dp" android:src="@drawable/ic_qiuda" /> <Button android:layout_marginLeft="30dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="點擊我" /> </LinearLayout>
然后新建一個Service的子類,MyService:
public class MyService extends Service {
public static final String TAG = "MyService";
@Override
public void onCreate() {
super.onCreate();
Notification notification = new Notification(R.drawable.ic_launcher,
"JcMan", System.currentTimeMillis());
RemoteViews view = new RemoteViews(getPackageName(),R.layout.notification);
notification.contentView = view;
startForeground(1, notification);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
可以看到,在onCreate方法里面我們設置界面的不再是用LayoutInflater來得到界面,而是用RemoteViews來new出來一個界面,構造方法傳入的是包名和界面資源的ID即可,然后我們把notification.contentView設置成我們new出來的自定義界面即可。
小結
普通的Notification可以用來進行通知,但是當有特殊需要的時候,我們就需要自定義界面,而且有時候還需要對自定義的界面添加點擊的方法,如在上圖的界面里面有一個Button如何對Button的點擊事件進行響應,這是一個比較難的問題,因為這不是簡單的setOnClickListener就可以的,需要另外的實現(xiàn),需要用到廣播機制,我將會在下一篇文章中說明如何為Notification的自定義界面添加點擊事件。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Android使用MediaPlayer和TextureView實現(xiàn)視頻無縫切換
這篇文章主要為大家詳細介紹了Android使用MediaPlayer和TextureView實現(xiàn)視頻無縫切換,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-10-10
Android滑動刪除數(shù)據(jù)功能的實現(xiàn)代碼
這篇文章主要介紹了Android滑動刪除功能2017-01-01
Flutter?將Dio請求轉發(fā)原生網(wǎng)絡庫的實現(xiàn)方案
這篇文章主要介紹了Flutter?將Dio請求轉發(fā)原生網(wǎng)絡庫,需要注意添加NativeNetInterceptor,如果有多個攔截器,例如LogInterceptors等等,需要將NativeNetInterceptor放到最后,需要的朋友可以參考下2022-05-05

