android 通知栏点击事件及8.0适配
16lz
2021-01-23
设置 通知栏
private void setNotification(String filePath, String recordType) { notificationManager = (NotificationManager) mainActivity.getSystemService(Context.NOTIFICATION_SERVICE); // ========= 重点1 ============ NotificationChannel notificationChannel= null; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) { notificationChannel = new NotificationChannel("channel_id","channel_name", NotificationManager.IMPORTANCE_HIGH); notificationChannel.setDescription("chanel_description"); notificationChannel.enableVibration(true); notificationChannel.setVibrationPattern(new long[]{100, 200, 200, 200}); notificationManager.createNotificationChannel(notificationChannel); } builder = new NotificationCompat.Builder(mainActivity, mainActivity.getPackageName()); remoteViews = new RemoteViews(mainActivity.getPackageName(), R.layout.notification_layout); notification = builder .setSmallIcon(R.mipmap.nl_icon)//通知的构建过程基本与默认相同 .setWhen(System.currentTimeMillis()) .setAutoCancel(false) .setShowWhen(false) .setLocalOnly(true) .setPriority(Notification.PRIORITY_MAX) .setCustomContentView(remoteViews) .setVibrate(new long[]{100, 200, 200, 200}) .build(); notification.flags=Notification.FLAG_ONGOING_EVENT; notification.flags |= Notification.FLAG_NO_CLEAR; Intent intentOne = new Intent(mainActivity, MainActivity.class); PendingIntent pendingIntentOne = PendingIntent.getActivity(mainActivity, 0, intentOne, PendingIntent.FLAG_UPDATE_CURRENT); Intent intent = new Intent("notification_clicked"); // ========= 重点2============ PendingIntent pendingIntent = PendingIntent.getBroadcast(mainActivity, PENDINGINTENT_REQUEST_CODE, intent,PendingIntent.FLAG_UPDATE_CURRENT); remoteViews.setTextViewText(R.id.nl_tv_filename,filePath); remoteViews.setTextViewText(R.id.nl_tv_type,recordType); remoteViews.setOnClickPendingIntent(R.id.nl_rl_parent, pendingIntent); notificationManager.notify(NOTIFICATION_ID, notification); }
注册动态广播
IntentFilter intent=new IntentFilter("notification_clicked"); // ========= 重点3============nlBroadcastReceiver=new NLBroadcastReceiver();mainActivity.registerReceiver(nlBroadcastReceiver,intent);
接收广播
class NLBroadcastReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { LogTools.i(TAG,"onReceive=intent=action="+intent.getAction()); if(intent.getAction().equals("notification_clicked")){ // ========= 重点4 ============ } } }
取消通知栏
private void cancelNotification(){ notificationManager = (NotificationManager) mainActivity.getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.cancel(NOTIFICATION_ID); }
注销广播
mainActivity.unregisterReceiver(nlBroadcastReceiver );
更多相关文章
- android获取通知权限
- Android学习之期末复习重点整理
- Android通知Notification的使用
- Android 8.0 设置默认闹钟提示音或者默认通知提示音
- android通知栏消息
- 【Android 开发教程】Toast通知
- Android设置通知栏/状态栏透明改变通知栏颜色和app最上部分颜色
- Android 通知Notification的两种实现方法
- Android点击通知栏,不启动新的activity