kotlin实现通知栏提醒功能示例代码

一、概述

2019年英雄联盟LPL赛区赛季赛打得火热,作为一个RNG粉丝,想通过app实现RNG赛程提醒,于是就有了这次技术实践。我在网上找了很久,几乎没找到使用kotlin实现通知栏提醒的合适的文章,于是就到安卓官网看文档,一边翻译一边研究,最终实现了一个简单的通知栏提醒。又研究了定时任务,但没有成功,还望看到的大佬给个锦囊。

二、环境

kotlin版本:1.3.31

android studio版本:3.4.1

在华为手机android 9 API28 环境下测试通过

三、实现

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)
 }
}

四、总结

对于报错部分,可以使用 Alt+Enter 组合键完成错误更正。

详细的通知使用,请转到官网研究。developer.android.google.cn/training/no

初次发文,若有不足的地方,还请指正。成品截图

kotlin实现通知栏提醒功能示例代码

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对我们的支持。

相关文章

Android 如何解决dialog弹出时无法捕捉Activity的back事件 在...
Android实现自定义带文字和图片的Button 在Android开发中经常...
Android 关于长按back键退出应用程序的实现最近在做一个Andr...
android自带的时间选择器只能精确到分,但是对于某些应用要求...