温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

使用kotlin怎么实现一个通知栏提醒功能

发布时间:2021-04-09 16:03:05 来源:亿速云 阅读:378 作者:Leah 栏目:移动开发

本篇文章为大家展示了使用kotlin怎么实现一个通知栏提醒功能,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

1、创建一个 Empty Activity 项目后,编辑 activity_main.xml 文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:orientation="vertical"
 xmlns:android="http://schemas.android.com/apk/res/android">
 <Button
  android:onClick="showNotification"
  android:text="显示通知"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"/>
</LinearLayout>

2、在类  MainActivity 创建 showNotification 方法

fun showNotification(view: View)
{
 // CHANNEL_ID:通道ID,可在类 MainActivity 外自定义。如:val CHANNEL_ID = 'msg_1'
 val builder = NotificationCompat.Builder(this, CHANNEL_ID)
  .setSmallIcon(R.mipmap.ic_launcher)
  .setContentTitle("RNG赛程提醒")
  .setContentText("今天晚上19:00,RNG对阵IG")
  // 通知优先级,可以设置为int型,范围-2至2
  .setPriority(NotificationCompat.PRIORITY_MAX )
 // 显示通知
 with(NotificationManagerCompat.from(this)) {
  notify(1, builder.build())
 }
}

3、为了兼容Android 8.0及更高版本,传递通知之前,必须在系统中注册应用程序的通知通道。创建好后在 onCreate 函数内调用

private fun createNotificationChannel()
{
 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
  val name = getString(R.string.channel_name)
  val descriptionText = getString(R.string.channel_description)
  // 提醒式通知(横幅显示),不过大部分需要手动授权
  val importance = NotificationManager.IMPORTANCE_HIGH
  val channel = NotificationChannel(CHANNEL_ID, name, importance).apply {description = descriptionText}
  // 注册通道(频道)
  val notificationManager: NotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
  notificationManager.createNotificationChannel(channel)
 }
}

上述内容就是使用kotlin怎么实现一个通知栏提醒功能,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI