Android自定義Notification添加點(diǎn)擊事件
前言
在上一篇文章中《Notification自定義界面》中我們實(shí)現(xiàn)了自定義的界面,那么我們該怎么為自定義的界面添加點(diǎn)擊事件呢?像酷狗在通知欄 有“上一首”,“下一首”等控制按鈕,我們需要對按鈕的點(diǎn)擊事件進(jìn)行響應(yīng),不過方法和之前的點(diǎn)擊設(shè)置不一樣,需要另外處理,下面我將進(jìn)行簡單的說明。
實(shí)現(xiàn)
同樣,我們需要一個Service的子類MyService,然后在MyService的onCreate中設(shè)置,如下代碼:
public class MyService extends Service {
public static final String ONCLICK = "com.app.onclick";
private BroadcastReceiver receiver_onclick = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ONCLICK)) {
Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(1000);
}
}
};
@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;
IntentFilter filter_click = new IntentFilter();
filter_click.addAction(ONCLICK);
//注冊廣播
registerReceiver(receiver_onclick, filter_click);
Intent Intent_pre = new Intent(ONCLICK);
//得到PendingIntent
PendingIntent pendIntent_click = PendingIntent.getBroadcast(this, 0, Intent_pre, 0);
//設(shè)置監(jiān)聽
notification.contentView.setOnClickPendingIntent(R.id.btn,pendIntent_click);
//前臺運(yùn)行
startForeground(1, notification);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
可以看到,我們先得到BroadcastReceiver的一個對象,然后在onReceiver里面實(shí)現(xiàn)我們的操作,我設(shè)置成點(diǎn)擊時候手機(jī)震動一秒鐘,當(dāng)然不要忘記在配置文件添加震動的權(quán)限,不然到時候就會出錯了。如果對廣播沒有了解的,那么可以先去了解一下廣播的機(jī)制,這里我使用的是動態(tài)注冊廣播的方法,還有另外一種方法來注冊,不過我更喜歡動態(tài)注冊的罷了。
小結(jié)
看到在Notification添加一個ProgressBar來實(shí)現(xiàn)下載的進(jìn)度提示,這里需要用到更新Notification界面的知識,雖然和在Activity中更新界面不太一樣,但是也不是在復(fù)雜,因?yàn)槲也]有用到這方面的知識,所以這里就不給大家介紹了,有興趣的可以搜相關(guān)的內(nèi)容。
- Android中通過Notification&NotificationManager實(shí)現(xiàn)消息通知
- Android編程實(shí)現(xiàn)google消息通知功能示例
- Android之開發(fā)消息通知欄
- Android消息通知欄的實(shí)現(xiàn)方法介紹
- Android中AlarmManager+Notification實(shí)現(xiàn)定時通知提醒功能
- Android 中Notification彈出通知實(shí)現(xiàn)代碼
- Android編程使用Service實(shí)現(xiàn)Notification定時發(fā)送功能示例
- Android 通知使用權(quán)(NotificationListenerService)的使用
- android使用NotificationListenerService監(jiān)聽通知欄消息
- Android消息通知Notification常用方法(發(fā)送消息和接收消息)
相關(guān)文章
Android 自定義精美界面包含選項(xiàng)菜單 上下文菜單及監(jiān)聽詳解流程
這篇文章主要介紹了一個Android實(shí)例小項(xiàng)目,它包含了選項(xiàng)菜單、上下文菜單及其對應(yīng)的監(jiān)聽事件,它很小,但這部分功能在Android開發(fā)中很常見,需要的朋友來看看吧2021-11-11
Dagger2 Android依賴注入學(xué)習(xí)筆記
這篇文章主要介紹了Dagger2 Android依賴注入學(xué)習(xí)筆記,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-06-06
Android 為ListView添加分段標(biāo)頭的方法
下面小編就為大家?guī)硪黄狝ndroid 為ListView添加分段標(biāo)頭的方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-04-04
Android Studio連接手機(jī)設(shè)備教程
這篇文章主要為大家詳細(xì)介紹了Android Studio連接手機(jī)設(shè)備教程,非常完整的連接步驟,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-07-07

