IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 移动开发 -> 创建Notification -> 正文阅读

[移动开发]创建Notification

1、定义变量和数据

package com.example.mynotification

import android.app.NotificationManager
import androidx.core.app.NotificationCompat

object InboxStyleMockData {
    const val mContentTitle = "5 new emails"
    const val mContentText = "from Jane, Jay, Alex +2 more"
    const val mNumberOfNewEmails = 5
    const val mPriority = NotificationCompat.PRIORITY_DEFAULT

    const val mBigContentTitle = "5 new emails from Jane, Jay, Alex +2"
    const val mSummaryText = "New emails"

    fun mIndividualEmailSummary() : ArrayList<String>{
        val list = ArrayList<String>()

        list.add("Jane Faab - Launch Party is here ...")
        list.add("Jay Walker - There's a turtle on the server!")
        list.add("Alex Chang - Check this out ...")
        list.add("Jane Johns- Check in code?")
        list.add("John Smith - Movies later ...")

        return list
    }

    fun mParticipants() : ArrayList<String>{
        val list = ArrayList<String>()

        list.add("Jane Fabb")
        list.add("Jay Walker")
        list.add("Alex Chang")
        list.add("Jane Johns")
        list.add("John Smith")

        return list
    }

    const val mChannelId = "channel_email_1"
    const val mChannelName = "Sample Email"

    const val mChannelDescription = "Sample Email Notifications"
    const val mChannelImportance = NotificationManager.IMPORTANCE_DEFAULT
    const val mChannelEnableVibrate = true
    const val mChannelLockscreenVisibility = NotificationCompat.VISIBILITY_PRIVATE


}

2、创建notification channel

package com.example.mynotification

import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.os.Build

class NotificationUtil {

    fun createInboxStyleNotificationChannel(context: Context):String{

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
            //The id of the channel
            val  channelId : String = InboxStyleMockData.mChannelId
            //The user-visible name of the channel
            val channelName : CharSequence = InboxStyleMockData.mChannelName
            val channelDescription : String = InboxStyleMockData.mChannelDescription
            val channelImportance : Int = InboxStyleMockData.mChannelImportance
            val channelEnableVibrate : Boolean = InboxStyleMockData.mChannelEnableVibrate
            val channelLockscreenVisibility : Int = InboxStyleMockData.mChannelLockscreenVisibility


            //Initializes NotificationChannel
            val notificationChannel = NotificationChannel(channelId,channelName,channelImportance)
            notificationChannel.description = channelDescription
            notificationChannel.enableVibration(channelEnableVibrate)
            notificationChannel.lockscreenVisibility = channelLockscreenVisibility

            //Adds NotificationChannel to system
            val notificationManager =
                context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
                notificationManager.createNotificationChannel(notificationChannel)

            return channelId
        }else{
            return ""
        }
    }

}

3、

定义notification id 和notification manger,并初始化notificationmanager

private val NOTIFICATION_ID = 888
    private lateinit var mNotificationManagerCompat: NotificationManagerCompat

 mNotificationManagerCompat = NotificationManagerCompat.from(this@MainActivity)

4、创建notification

 val notificationChannelId : String =
            NotificationUtil().createInboxStyleNotificationChannel(this)

        val inboxStyle =
            NotificationCompat.InboxStyle() //This title is slightly different than regular title
                .setBigContentTitle(InboxStyleMockData.mBigContentTitle) //available
                .setSummaryText(InboxStyleMockData.mSummaryText)

        for(summary in InboxStyleMockData.mIndividualEmailSummary()){
            inboxStyle.addLine(summary)
        }

        val mainIntent = Intent(this,MainActivity::class.java)

        val mainPendingIntent = PendingIntent.getActivity(
            this,
            0,
            mainIntent,
            PendingIntent.FLAG_CANCEL_CURRENT
        )

        val notificationCompatBuilder = NotificationCompat.Builder(
            applicationContext,
            notificationChannelId
        )

        notificationCompatBuilder.setStyle(inboxStyle)
            .setContentTitle(InboxStyleMockData.mBigContentTitle)
            .setContentText(InboxStyleMockData.mContentText)
            .setSmallIcon(R.drawable.ic_start_notification)
            .setLargeIcon(
                BitmapFactory.decodeResource(
                    resources,
                    R.drawable.ic_person
                )
            )
            .setContentIntent(mainPendingIntent)
            .setDefaults(NotificationCompat.DEFAULT_ALL)
            .setColor(
                ContextCompat.getColor(
                    applicationContext,
                    R.color.purple_500
                )
            )
            .setSubText(InboxStyleMockData.mNumberOfNewEmails.toString())
            .setCategory(Notification.CATEGORY_EMAIL)
            .setPriority(InboxStyleMockData.mPriority)
            .setVisibility(InboxStyleMockData.mChannelLockscreenVisibility)

         for(name in InboxStyleMockData.mParticipants()){
             notificationCompatBuilder.addPerson(name)
         }

        val notification = notificationCompatBuilder.build()
        mNotificationManagerCompat.notify(NOTIFICATION_ID,notification)
package com.example.mynotification

import android.app.Notification
import android.app.PendingIntent
import android.content.Intent
import android.graphics.BitmapFactory
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.content.ContextCompat

class MainActivity : AppCompatActivity(), View.OnClickListener {

    private val NOTIFICATION_ID = 888
    private lateinit var mNotificationManagerCompat: NotificationManagerCompat

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        mNotificationManagerCompat = NotificationManagerCompat.from(this@MainActivity)

        val btnInboxStyleNotification = findViewById<Button>(R.id.btn_inbox_style)
        btnInboxStyleNotification.setOnClickListener(this@MainActivity)
    }

    override fun onClick(v: View) {

        when(v.id){

            R.id.btn_inbox_style -> {
                generateInboxStyleNotification()
                return
            }

        }
    }

    private fun generateInboxStyleNotification(){
        val notificationChannelId : String =
            NotificationUtil().createInboxStyleNotificationChannel(this)

        val inboxStyle =
            NotificationCompat.InboxStyle() //This title is slightly different than regular title
                .setBigContentTitle(InboxStyleMockData.mBigContentTitle) //available
                .setSummaryText(InboxStyleMockData.mSummaryText)

        for(summary in InboxStyleMockData.mIndividualEmailSummary()){
            inboxStyle.addLine(summary)
        }

        val mainIntent = Intent(this,MainActivity::class.java)

        val mainPendingIntent = PendingIntent.getActivity(
            this,
            0,
            mainIntent,
            PendingIntent.FLAG_CANCEL_CURRENT
        )

        val notificationCompatBuilder = NotificationCompat.Builder(
            applicationContext,
            notificationChannelId
        )

        notificationCompatBuilder.setStyle(inboxStyle)
            .setContentTitle(InboxStyleMockData.mBigContentTitle)
            .setContentText(InboxStyleMockData.mContentText)
            .setSmallIcon(R.drawable.ic_start_notification)
            .setLargeIcon(
                BitmapFactory.decodeResource(
                    resources,
                    R.drawable.ic_person
                )
            )
            .setContentIntent(mainPendingIntent)
            .setDefaults(NotificationCompat.DEFAULT_ALL)
            .setColor(
                ContextCompat.getColor(
                    applicationContext,
                    R.color.purple_500
                )
            )
            .setSubText(InboxStyleMockData.mNumberOfNewEmails.toString())
            .setCategory(Notification.CATEGORY_EMAIL)
            .setPriority(InboxStyleMockData.mPriority)
            .setVisibility(InboxStyleMockData.mChannelLockscreenVisibility)

         for(name in InboxStyleMockData.mParticipants()){
             notificationCompatBuilder.addPerson(name)
         }

        val notification = notificationCompatBuilder.build()
        mNotificationManagerCompat.notify(NOTIFICATION_ID,notification)

    }
}

运行结果:?

点击该notification回到主界面:

注:

MAinActivity布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textStyle="bold"
        android:textSize="18sp"
        android:gravity="center"
        android:text="Click on the button to launch your Notification Style:"
       />

    <TextView
        android:id="@+id/tv_inbox_style_details"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="Demos email type app using INBOX_STYLE"
        android:layout_marginTop="25dp"
        />


    <Button
        android:id="@+id/btn_inbox_style"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="Launch Inbox Style Notification!"
        />


    <TextView
        android:id="@+id/tv_big_image_style_details"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="Demos email type app using BIG_PICTURE_STYLE"
        android:layout_marginTop="25dp"
        />


    <Button
        android:id="@+id/btn_big_image_style"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="Launch Big Image Style Notification!"
        />
</LinearLayout>

  移动开发 最新文章
Vue3装载axios和element-ui
android adb cmd
【xcode】Xcode常用快捷键与技巧
Android开发中的线程池使用
Java 和 Android 的 Base64
Android 测试文字编码格式
微信小程序支付
安卓权限记录
知乎之自动养号
【Android Jetpack】DataStore
上一篇文章      下一篇文章      查看所有文章
加:2022-05-18 17:46:02  更:2022-05-18 17:48:18 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/25 1:37:45-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码