查询权限
/** * 检查通知权限 */ private fun checkNotifyPermissionStatus() { context?.let { context -> val manager = NotificationManagerCompat.from(context) // areNotificationsEnabled方法的有效性官方只最低支持到API 19,低于19的仍可调用此方法不过只会返回true,即默认为用户已经开启了通知。 val isOpened = manager.areNotificationsEnabled() if (!isOpened) { mBinding.permissionTips.visibility = View.VISIBLE mBinding.goOpenPermission.visibility = View.VISIBLE } else { mBinding.permissionTips.visibility = View.GONE mBinding.goOpenPermission.visibility = View.GONE } } }
引导用户授权
/** * 跳转到允许通知界面 */ private void jumpNoticeInterface() { Intent localIntent = new Intent(); localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); if (Build.VERSION.SDK_INT >= 9) { localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS"); localIntent.setData(Uri.fromParts("package", getContext().getPackageName(), null)); } else if (Build.VERSION.SDK_INT <= 8) { localIntent.setAction(Intent.ACTION_VIEW); localIntent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails"); localIntent.putExtra("com.android.settings.ApplicationPkgName", getContext().getPackageName()); } startActivity(localIntent); }
创建通知
context?.let { context -> val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val channel = NotificationChannel("nomal", "Nomal", NotificationManager.IMPORTANCE_DEFAULT) manager.createNotificationChannel(channel) } val notification = NotificationCompat.Builder(context, "nomal") .setContentTitle("this is title") .setContentText("content") .setSmallIcon(R.mipmap.sym_def_app_icon) .build() manager.notify(1, notification) }
携带PendingIntent的通知
val manager= getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.O){ val channel= NotificationChannel("nomal","Nomal", NotificationManager.IMPORTANCE_DEFAULT) manager.createNotificationChannel(channel) } sendAotice.setOnClickListener { val intent=Intent(this,NoticeActivity::class.java) val pi=PendingIntent.getActivity(this,0,intent,0) val notification=NotificationCompat.Builder(this,"nomal") .setContentTitle("this is title") .setContentText("this is content") .setSmallIcon(R.mipmap.ic_launcher) .setContentIntent(pi) .build() manager.notify(1,notification) }
End
本文来自博客园,作者:观心静 ,转载请注明原文链接:https://www.cnblogs.com/guanxinjing/p/15829197.html
本文版权归作者和博客园共有,欢迎转载,但必须给出原文链接,并保留此段声明,否则保留追究法律责任的权利。