欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Android自定義Notification添加點(diǎn)擊事件

 更新時(shí)間:2017年11月30日 08:36:43   作者:潘建成  
這篇文章主要為大家詳細(xì)介紹了Android自定義Notification添加點(diǎn)擊事件,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

前言

在上一篇文章中《Notification自定義界面》中我們實(shí)現(xiàn)了自定義的界面,那么我們?cè)撛趺礊樽远x的界面添加點(diǎn)擊事件呢?像酷狗在通知欄 有“上一首”,“下一首”等控制按鈕,我們需要對(duì)按鈕的點(diǎn)擊事件進(jìn)行響應(yīng),不過方法和之前的點(diǎn)擊設(shè)置不一樣,需要另外處理,下面我將進(jìn)行簡(jiǎn)單的說明。

實(shí)現(xiàn)

同樣,我們需要一個(gè)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);
  //注冊(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)聽
  notification.contentView.setOnClickPendingIntent(R.id.btn,pendIntent_click);
  //前臺(tái)運(yùn)行
  startForeground(1, notification);
 }
 @Override
 public IBinder onBind(Intent intent) {
  return null;
 }
}

可以看到,我們先得到BroadcastReceiver的一個(gè)對(duì)象,然后在onReceiver里面實(shí)現(xiàn)我們的操作,我設(shè)置成點(diǎn)擊時(shí)候手機(jī)震動(dòng)一秒鐘,當(dāng)然不要忘記在配置文件添加震動(dòng)的權(quán)限,不然到時(shí)候就會(huì)出錯(cuò)了。如果對(duì)廣播沒有了解的,那么可以先去了解一下廣播的機(jī)制,這里我使用的是動(dòng)態(tài)注冊(cè)廣播的方法,還有另外一種方法來注冊(cè),不過我更喜歡動(dòng)態(tài)注冊(cè)的罷了。

小結(jié)

看到在Notification添加一個(gè)ProgressBar來實(shí)現(xiàn)下載的進(jìn)度提示,這里需要用到更新Notification界面的知識(shí),雖然和在Activity中更新界面不太一樣,但是也不是在復(fù)雜,因?yàn)槲也]有用到這方面的知識(shí),所以這里就不給大家介紹了,有興趣的可以搜相關(guān)的內(nèi)容。

相關(guān)文章

最新評(píng)論