专栏名称: 男儿当自强
软件工程师
目录
相关文章推荐
今天看啥  ›  专栏  ›  男儿当自强

kotlin-实现通知栏提醒

男儿当自强  · 掘金  ·  · 2019-08-10 04:20

文章预览

阅读 37

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…

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

成品截图



………………………………

原文地址:访问原文地址
快照地址: 访问文章快照
总结与预览地址:访问总结与预览