最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Android Notification通知使用詳解

 更新時間:2022年09月08日 08:56:19   作者:愿天深海  
消息通知(Notification)是Android系統(tǒng)中比較有特色的一個功能,當某個應用程序希望用戶發(fā)出一些提示信息,而該應用又不在前臺運行時,就可以借助通知來實現(xiàn)

在Android應用的開發(fā)中,必然會遇上通知的開發(fā)需求,本文主要講一下Android中的通知 Notification的簡單基本使用,主要包含創(chuàng)建通知渠道、初始化通知、顯示通知、顯示圖片通知、通知點擊、以及配合WorkManager發(fā)送延遲通知。

Demo下載

創(chuàng)建通知渠道

首先,創(chuàng)建幾個常量和變量,其中渠道名是會顯示在手機設置-通知里app對應展示的通知渠道名稱,一般基于通知作用取名。

    companion object {
        //渠道Id
        private const val CHANNEL_ID = "渠道Id"
        //渠道名
        private const val CHANNEL_NAME = "渠道名-簡單通知"
        //渠道重要級
        private const val CHANNEL_IMPORTANCE = NotificationManager.IMPORTANCE_DEFAULT
    }
    private lateinit var context: Context
    //Notification的ID
    private var notifyId = 100
    private lateinit var manager: NotificationManager
    private lateinit var builder: NotificationCompat.Builder

然后獲取系統(tǒng)通知服務,創(chuàng)建通知渠道,其中因為通知渠道是Android8.0才有的,所以增加一個版本判斷:

        //獲取系統(tǒng)通知服務
        manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        //創(chuàng)建通知渠道,Android8.0及以上需要
        createChannel()
    private fun createChannel() {
        //創(chuàng)建通知渠道,Android8.0及以上需要
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
            return
        }
        val notificationChannel = NotificationChannel(
            CHANNEL_ID,
            CHANNEL_NAME,
            CHANNEL_IMPORTANCE
        )
        manager.createNotificationChannel(notificationChannel)
    }

初始化通知

先生成NotificationCompat.Builder,然后初始化通知Builder的通用配置:

        builder = NotificationCompat.Builder(context.applicationContext, CHANNEL_ID)
        initNotificationBuilder()
    /**
     * 初始化通知Builder的通用配置
     */
    private fun initNotificationBuilder() {
        builder
            .setAutoCancel(true) //設置這個標志當用戶單擊面板就可以讓通知自動取消
            .setSmallIcon(R.drawable.ic_reminder) //通知的圖標
            .setWhen(System.currentTimeMillis()) //通知產(chǎn)生的時間,會在通知信息里顯示
            .setDefaults(Notification.DEFAULT_ALL)
    }

此外builder還有setVibrate、setSound、setStyle等方法,按需配置即可。

顯示通知

給builder設置需要通知需要顯示的title和content,然后通過builder.build()生成生成通知Notification,manager.notify()方法將通知發(fā)送出去。

    fun configNotificationAndSend(title: String, content: String){
        builder.setContentTitle(title)
            .setContentText(content)
        val notification = builder.build()
        //發(fā)送通知
        manager.notify(notifyId, notification)
        //id自增
        notifyId++
    }

最簡單的通知顯示至此上面三步就完成了。

效果如下圖:

顯示圖片通知

當通知內(nèi)容過多一行展示不下時,可以通過設置

builder.setStyle(NotificationCompat.BigTextStyle().bigText(content)) //設置可以顯示多行文本

這樣通知就能收縮和展開,顯示多行文本。

另外setStyle還可以設置圖片形式的通知:

setStyle(NotificationCompat.BigPictureStyle().bigPicture(BitmapFactory.decodeResource(resources,R.drawable.logo)))//設置圖片樣式

效果如下圖:

通知點擊

目前為止的通知還只是顯示,因為設置了builder.setAutoCancel(true),點擊通知之后通知會自動消失,除此之外還沒有其他操作。

給builder設置setContentIntent(PendingIntent)就能有通知點擊之后的其他操作了。PendingIntent可以看作是對Intent的一個封裝,但它不是立刻執(zhí)行某個行為,而是滿足某些條件或觸發(fā)某些事件后才執(zhí)行指定的行為。PendingIntent獲取有三種方式:Activity、Service和BroadcastReceiver獲取。通過對應方法PendingIntent.getActivity、PendingIntent.getBroadcast、PendingIntent.getService就能獲取。

這里就示例一下PendingIntent.getBroadcast和PendingIntent.getActivity

PendingIntent.getBroadcast

首先創(chuàng)建一個BroadcastReceiver:

class NotificationHandleReceiver : BroadcastReceiver() {
    companion object {
        const val NOTIFICATION_HANDLE_ACTION = "notification_handle_action"
        const val NOTIFICATION_LINK = "notificationLink"
        const val TAG = "NotificationReceiver"
    }
    override fun onReceive(context: Context, intent: Intent?) {
        if (intent?.action == NOTIFICATION_HANDLE_ACTION) {
            val link = intent.getStringExtra(NOTIFICATION_LINK)
        }
    }
}

別忘了在清單文件中還需要靜態(tài)注冊BroadcastReceiver:

    <receiver
        android:name=".NotificationHandleReceiver"
        android:exported="false">
        <intent-filter>
            <action android:name="notification_handle_action" />
        </intent-filter>
    </receiver>

然后創(chuàng)建一個上面BroadcastReceiver的Intent,在intent.putExtra傳入相應的點擊通知之后需要識別的操作:

   fun generateDefaultBroadcastPendingIntent(linkParams: (() -> String)?): PendingIntent {
        val intent = Intent(NotificationHandleReceiver.NOTIFICATION_HANDLE_ACTION)
        intent.setPackage(context.packageName)
        linkParams?.let {
            val params = it.invoke()
            intent.putExtra(NotificationHandleReceiver.NOTIFICATION_LINK, params)
        }
        return PendingIntent.getBroadcast(
            context,
            notifyId,
            intent,
            PendingIntent.FLAG_IMMUTABLE
        )
    }

這樣生成的PendingIntent再builder.setContentIntent(pendingIntent),在我們點擊通知之后,NotificationHandleReceiver的onReceive里就會收到信息了,根據(jù)信息處理后續(xù)操作即可。

PendingIntent.getActivity

Activity的PendingIntent用于跳轉(zhuǎn)到指定activity,創(chuàng)建一個跳轉(zhuǎn)activity的Intent(同普通的頁面跳轉(zhuǎn)的Intent),也是同上面在intent.putExtra傳入相應的點擊通知之后需要識別的操作:

        val intent = Intent(this, XXXX::class.java).apply {
            putExtra("title", title).putExtra("content", content)
        }
        return PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_IMMUTABLE)

也是這樣生成的PendingIntent再builder.setContentIntent(pendingIntent),在我們點擊通知之后,就會跳轉(zhuǎn)到對應的activity頁面,然后intent里就會收到信息了,根據(jù)信息處理后續(xù)操作即可。

Android12之PendingIntent特性

行為變更:以 Android 12 為目標平臺的應用

查看上面關于Android12的特性

在Android12平臺上有關于PendingIntent的兩點特性:

一是待處理 intent 可變性,必須為應用創(chuàng)建的每個PendingIntent對象指定可變性,這也是上面創(chuàng)建PendingIntent時需要設置flag為PendingIntent.FLAG_IMMUTABLE。

二是通知 trampoline 限制,以 Android 12 或更高版本為目標平臺的應用無法從用作通知 trampoline 的服務廣播接收器中啟動 activity。換言之,當用戶點按通知或通知中的操作按鈕時,您的應用無法在服務或廣播接收器內(nèi)調(diào)用startActivity()。所以當需要點擊通知實現(xiàn)activity跳轉(zhuǎn)時,需要使用PendingIntent. getActivity,而不是使用PendingIntent.getBroadcast,然后在BroadcastReceiver里實現(xiàn)activity跳轉(zhuǎn),后者方式在Android 12 或更高版本為目標平臺的應用中將被限制。

配合WorkManager發(fā)送延遲通知

配合上WorkManager,就能實現(xiàn)發(fā)送延遲通知,主要是通過OneTimeWorkRequest的延遲特性。

創(chuàng)建一個延遲的OneTimeWorkRequest,加入WorkManager隊列中:

    fun sendWorkRequest(
        context: Context,
        reminderId: Int,
        title: String,
        content: String,
        link: String,
        triggerTime: Long
    ): OneTimeWorkRequest {
        val duration = triggerTime - System.currentTimeMillis()
        val data =
            Data.Builder().putInt(REMINDER_WORKER_DATA_ID, reminderId).putString(REMINDER_WORKER_DATA_TITLE, title)
                .putString(REMINDER_WORKER_DATA_CONTENT, content).putString(REMINDER_WORKER_DATA_LINK, link)
                .build()
        val uniqueWorkName =
            "reminderData_${reminderId}"
        val request = OneTimeWorkRequest.Builder(ReminderWorker::class.java)
            .setInitialDelay(duration, TimeUnit.MILLISECONDS)
            .setInputData(data)
            .build()
        WorkManager.getInstance(context)
            .enqueueUniqueWork(uniqueWorkName, ExistingWorkPolicy.REPLACE, request)
        return request
    }

然后在doWork方法中拿到數(shù)據(jù)進行我們上面的通知發(fā)送顯示即可。具體關于OneTimeWorkRequest的使用在本文中就不詳細說明了。當需要發(fā)送延遲通知時,知道可以通過配合WorkManager實現(xiàn)。

Android13 通知權限

在目前最新的Android 13(API 級別 33)上對于通知增加了權限限制,具體可看官方描述:

通知運行時權限

到此這篇關于Android Notification通知使用詳解的文章就介紹到這了,更多相關Android Notification內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論

甘孜县| 禹城市| 舟曲县| 灵山县| 长岭县| 布尔津县| 射洪县| 景洪市| 沙雅县| 南平市| 黑山县| 新疆| 怀宁县| 珲春市| 宣化县| 仁寿县| 廊坊市| 长沙县| 大荔县| 壤塘县| 南乐县| 红桥区| 延川县| 宜君县| 观塘区| 定边县| 建水县| 罗甸县| 时尚| 比如县| 前郭尔| 泾阳县| 翁源县| 寿宁县| 佛坪县| 南华县| 本溪市| 南涧| 博湖县| 明水县| 耿马|