欢迎来到代码驿站!

Android代码

当前位置:首页 > 移动开发 > Android代码

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

时间:2021-04-14 09:06:26|栏目:Android代码|点击:

一、概述

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

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

总结

上一篇:Android的搜索框架实例详解

栏    目:Android代码

下一篇:使用CursorLoader异步加载数据

本文标题:kotlin实现通知栏提醒功能示例代码

本文地址:http://www.codeinn.net/misctech/101299.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有