前言
在上一篇文章中《Notification自定義界面》中我們實(shí)現(xiàn)了自定義的界面,那么我們?cè)撛趺礊樽远x的界面添加點(diǎn)擊事件呢?像酷狗在通知欄 有“上一首”,“下一首”等控制按鈕,我們需要對(duì)按鈕的點(diǎn)擊事件進(jìn)行響應(yīng),不過(guò)方法和之前的點(diǎn)擊設(shè)置不一樣,需要另外處理,下面我將進(jìn)行簡(jiǎn)單的說(shuō)明。
實(shí)現(xiàn)
同樣,我們需要一個(gè)Service的子類(lèi)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); //注冊(cè)廣播 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)聽(tīng) notification.contentView.setOnClickPendingIntent(R.id.btn,pendIntent_click); //前臺(tái)運(yùn)行 startForeground(1, notification); } @Override public IBinder onBind(Intent intent) { return null; } }