android监听通知栏点击事件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/LosingCarryJie/article/details/80316786

核心思想:

使用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

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页