Android自定義Notification添加點擊事件
前言
在上一篇文章中《Notification自定義界面》中我們實現了自定義的界面,那么我們該怎么為自定義的界面添加點擊事件呢?像酷狗在通知欄 有“上一首”,“下一首”等控制按鈕,我們需要對按鈕的點擊事件進行響應,不過方法和之前的點擊設置不一樣,需要另外處理,下面我將進行簡單的說明。
實現
同樣,我們需要一個Service的子類MyService,然后在MyService的onCreate中設置,如下代碼:
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);
//設置監(jiān)聽
notification.contentView.setOnClickPendingIntent(R.id.btn,pendIntent_click);
//前臺運行
startForeground(1, notification);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
可以看到,我們先得到BroadcastReceiver的一個對象,然后在onReceiver里面實現我們的操作,我設置成點擊時候手機震動一秒鐘,當然不要忘記在配置文件添加震動的權限,不然到時候就會出錯了。如果對廣播沒有了解的,那么可以先去了解一下廣播的機制,這里我使用的是動態(tài)注冊廣播的方法,還有另外一種方法來注冊,不過我更喜歡動態(tài)注冊的罷了。
小結
看到在Notification添加一個ProgressBar來實現下載的進度提示,這里需要用到更新Notification界面的知識,雖然和在Activity中更新界面不太一樣,但是也不是在復雜,因為我并沒有用到這方面的知識,所以這里就不給大家介紹了,有興趣的可以搜相關的內容。
- Android中通過Notification&NotificationManager實現消息通知
- Android編程實現google消息通知功能示例
- Android之開發(fā)消息通知欄
- Android消息通知欄的實現方法介紹
- Android中AlarmManager+Notification實現定時通知提醒功能
- Android 中Notification彈出通知實現代碼
- Android編程使用Service實現Notification定時發(fā)送功能示例
- Android 通知使用權(NotificationListenerService)的使用
- android使用NotificationListenerService監(jiān)聽通知欄消息
- Android消息通知Notification常用方法(發(fā)送消息和接收消息)
相關文章
Android 自定義精美界面包含選項菜單 上下文菜單及監(jiān)聽詳解流程
這篇文章主要介紹了一個Android實例小項目,它包含了選項菜單、上下文菜單及其對應的監(jiān)聽事件,它很小,但這部分功能在Android開發(fā)中很常見,需要的朋友來看看吧2021-11-11

