Android 8.0实现发送通知
在Android8.0以后,针对Notification通知api做了修改,新增了通知渠道(NotificationCannel)。下面就把demo的详细代码记录下:
1.Application为NotificationManager添加通知频道
importandroid.app.Application; importcom.xinrui.ndkapp.notification.NotificationChannels; publicclassNdkApplicationextendsApplication{ @Override publicvoidonCreate(){ super.onCreate(); NotificationChannels.createAllNotificationChannels(this); } }
2.NotificationChannels类
publicclassNotificationChannels{ publicfinalstaticStringCRITICAL="critical"; publicfinalstaticStringIMPORTANCE="importance"; publicfinalstaticStringDEFAULT="default"; publicfinalstaticStringLOW="low"; publicfinalstaticStringMEDIA="media"; publicstaticvoidcreateAllNotificationChannels(Contextcontext){ NotificationManagernm=(NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE); if(nm==null){ return; } NotificationChannelmediaChannel=newNotificationChannel( MEDIA, context.getString(R.string.app_name), NotificationManager.IMPORTANCE_DEFAULT); mediaChannel.setSound(null,null); mediaChannel.setVibrationPattern(null); nm.createNotificationChannels(Arrays.asList( newNotificationChannel( CRITICAL, context.getString(R.string.app_name), NotificationManager.IMPORTANCE_HIGH), newNotificationChannel( IMPORTANCE, context.getString(R.string.app_name), NotificationManager.IMPORTANCE_DEFAULT), newNotificationChannel( DEFAULT, context.getString(R.string.app_name), NotificationManager.IMPORTANCE_LOW), newNotificationChannel( LOW, context.getString(R.string.app_name), NotificationManager.IMPORTANCE_MIN), //customnotificationchannel mediaChannel )); } }
3.发送通知
publicvoidsendSimpleNotification(Contextcontext,NotificationManagernm){ //创建点击通知时发送的广播 Intentintent=newIntent(context,NotificationMonitorService.class); intent.setAction("android.service.notification.NotificationListenerService"); PendingIntentpi=PendingIntent.getService(context,0,intent,0); //创建删除通知时发送的广播 IntentdeleteIntent=newIntent(context,NotificationMonitorService.class); deleteIntent.setAction(Intent.ACTION_DELETE); PendingIntentdeletePendingIntent=PendingIntent.getService(context,0,deleteIntent,0); //创建通知 Notification.Buildernb=newNotification.Builder(context,NotificationChannels.DEFAULT) //设置通知左侧的小图标 .setSmallIcon(R.drawable.ic_notification) //设置通知标题 .setContentTitle("Simplenotification") //设置通知内容 .setContentText("Demoforsimplenotification!") //设置点击通知后自动删除通知 .setAutoCancel(true) //设置显示通知时间 .setShowWhen(true) //设置通知右侧的大图标 .setLargeIcon(BitmapFactory.decodeResource(context.getResources(),R.drawable.ic_notifiation_big)) //设置点击通知时的响应事件 .setContentIntent(pi) //设置删除通知时的响应事件 .setDeleteIntent(deletePendingIntent); //发送通知 nm.notify(Notificaitons.NOTIFICATION_SAMPLE,nb.build()); }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。