android監聽通知欄點擊事件

核心思想:

使用BroadCastReceiver

1 新建一個BroadCastReceiver類,並且在清單文件中註冊!!

  <receiver
         android:name=".NotificationClickReceiver">
  </receiver>
public class NotificationClickReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        //todo 跳轉之前要處理的邏輯
        Log.i("TAG", "userClick:我被點擊啦!!! ");
        Intent newIntent = new Intent(context, Main2Activity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(newIntent);
    }
}

2 在你需要創建通知欄的地方

 NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
        Notification.Builder builder1 = new Notification.Builder(MainActivity.this);
        builder1.setSmallIcon(R.drawable.ic_launcher); //設置圖標
        builder1.setTicker("顯示第二個通知");
        builder1.setContentTitle("通知"); //設置標題
        builder1.setContentText("點擊查看詳細內容"); //消息內容
        builder1.setWhen(System.currentTimeMillis()); //發送時間
        builder1.setDefaults(Notification.DEFAULT_ALL); //設置默認的提示音,振動方式,燈光
        builder1.setAutoCancel(true);//打開程序後圖標消失
        Intent intent =new Intent (MainActivity.this,NotificationClickReceiver.class);
        PendingIntent pendingIntent =PendingIntent.getBroadcast(MainActivity.this, 0, intent, 0);
        builder1.setContentIntent(pendingIntent);
        Notification notification1 = builder1.build();
        notificationManager.notify(124, notification1); // 通過通知管理器發送通知

注意其中這兩句代碼

Intent intent =new Intent (MainActivity.this,NotificationClickReceiver.class);
        PendingIntent pendingIntent =PendingIntent.getBroadcast(MainActivity.this, 0, intent, 0);

getBroadcast!
getBroadcast!
getBroadcast!

如果需要攜帶什麼參數就在這裏的intent包裹即可,NotificationClickReceiver可以接收到發送過來的intent

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章