在android8.0以后,针对notification 通知api做了修改,新增了通知渠道(notificationcannel)。下面就把demo的详细代码记录下:
1.application 为notificationmanager添加通知频道
import android.app.application; import com.xinrui.ndkapp.notification.notificationchannels; public class ndkapplication extends application { @override public void oncreate() { super.oncreate(); notificationchannels.createallnotificationchannels(this); } }
2.notificationchannels 类
public class notificationchannels { public final static string critical = "critical"; public final static string importance = "importance"; public final static string default = "default"; public final static string low = "low"; public final static string media = "media"; public static void createallnotificationchannels(context context) { notificationmanager nm = (notificationmanager) context.getsystemservice(context.notification_service); if(nm == null) { return; } notificationchannel mediachannel = new notificationchannel( media, context.getstring(r.string.app_name), notificationmanager.importance_default); mediachannel.setsound(null,null); mediachannel.setvibrationpattern(null); nm.createnotificationchannels(arrays.aslist( new notificationchannel( critical, context.getstring(r.string.app_name), notificationmanager.importance_high), new notificationchannel( importance, context.getstring(r.string.app_name), notificationmanager.importance_default), new notificationchannel( default, context.getstring(r.string.app_name), notificationmanager.importance_low), new notificationchannel( low, context.getstring(r.string.app_name), notificationmanager.importance_min), //custom notification channel mediachannel )); } }
3.发送通知
public void sendsimplenotification(context context, notificationmanager nm) { //创建点击通知时发送的广播 intent intent = new intent(context, notificationmonitorservice.class); intent.setaction("android.service.notification.notificationlistenerservice"); pendingintent pi = pendingintent.getservice(context,0,intent,0); //创建删除通知时发送的广播 intent deleteintent = new intent(context,notificationmonitorservice.class); deleteintent.setaction(intent.action_delete); pendingintent deletependingintent = pendingintent.getservice(context,0,deleteintent,0); //创建通知 notification.builder nb = new notification.builder(context, notificationchannels.default) //设置通知左侧的小图标 .setsmallicon(r.drawable.ic_notification) //设置通知标题 .setcontenttitle("simple notification") //设置通知内容 .setcontenttext("demo for simple notification!") //设置点击通知后自动删除通知 .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()); }
以上就是android开发分享Android 8.0实现发送通知的全部内容,希望对大家的学习有所帮助,也希望大家多多支持<计算机技术网>。
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请点击右边联系管理员删除。
如若转载,请注明出处:https://www.ctvol.com/addevelopment/894969.html