前言
在上一篇文章中《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);  //設置監聽  notification.contentView.setOnClickPendingIntent(R.id.btn,pendIntent_click);  //前臺運行  startForeground(1, notification); } @Override public IBinder onBind(Intent intent) {  return null; }}可以看到,我們先得到BroadcastReceiver的一個對象,然后在onReceiver里面實現我們的操作,我設置成點擊時候手機震動一秒鐘,當然不要忘記在配置文件添加震動的權限,不然到時候就會出錯了。如果對廣播沒有了解的,那么可以先去了解一下廣播的機制,這里我使用的是動態注冊廣播的方法,還有另外一種方法來注冊,不過我更喜歡動態注冊的罷了。
小結
看到在Notification添加一個ProgressBar來實現下載的進度提示,這里需要用到更新Notification界面的知識,雖然和在Activity中更新界面不太一樣,但是也不是在復雜,因為我并沒有用到這方面的知識,所以這里就不給大家介紹了,有興趣的可以搜相關的內容。
新聞熱點
疑難解答