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

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

可以看到,我實現了一個簡單的界面,包括一個ImageView和Button,下面我就說說該如何實現它,其實很簡單。
實現
首先我們要準備一個界面文件:
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就可以的,需要另外的實現,需要用到廣播機制,我將會在下一篇文章中說明如何為Notification的自定義界面添加點擊事件。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Android實戰(zhàn)教程第六篇之一鍵鎖屏應用問題解決
這篇文章主要為大家詳細介紹了Android一鍵鎖屏應用開發(fā)過程中出現問題的解決方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-11-11
Android編程動態(tài)加載布局實例詳解【附demo源碼】
這篇文章主要介紹了Android編程動態(tài)加載布局,結合實例形式分析了Android動態(tài)加載布局的原理、操作步驟與相關實現技巧,需要的朋友可以參考下2016-10-10
解析Android中View轉換為Bitmap及getDrawingCache=null的解決方法
在android中經常會遇到View轉換為Bitmap的情形,本篇文章主要介紹了Android中View轉換為Bitmap及getDrawingCache=null的解決方法,有需要的可以了解一下。2016-11-11

