Android發(fā)送通知(Notification)

Android 8.0(<API 26)

// 創(chuàng)建通知(標(biāo)題、內(nèi)容、圖標(biāo))
Notification notification = new Notification.Builder(this)
        .setContentTitle("通知標(biāo)題")
        .setContentText("通知內(nèi)容")
        .setSmallIcon(R.mipmap.ic_launcher)
        .build();
// 創(chuàng)建通知管理器
NotificationManager manager = (NotificationManager) context
        .getSystemService(Context.NOTIFICATION_SERVICE);
// 發(fā)送通知
manager.notify(1, notification);

Android 8.0(≥API 26)

Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
// 1. 創(chuàng)建一個(gè)通知(必須設(shè)置channelId)
Context context = getApplicationContext();
String channelId = "ChannelId"; // 通知渠道
Notification notification = new Notification.Builder(context)
        .setChannelId(channelId) 
        .setSmallIcon(R.mipmap.icon_bill_64x64)
        .setContentTitle("通知標(biāo)題")
        .setContentText("通知內(nèi)容")
        .build();
// 2. 獲取系統(tǒng)的通知管理器(必須設(shè)置channelId)
NotificationManager notificationManager = (NotificationManager) context
        .getSystemService(NOTIFICATION_SERVICE);
NotificationChannel channel = new NotificationChannel(
        channelId,
        "通知的渠道名稱",
        NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
// 3. 發(fā)送通知(Notification與NotificationManager的channelId必須對(duì)應(yīng))
notificationManager.notify(id, notification);

PendingIntent

// 注意:PendingIntent.FLAG_UPDATE_CURRENT
Intent intent = new Intent(context, MainActivity.class); 
intent.putExtra(name, value);
PendingIntent pendingIntent = PendingIntent.getActivity(
        context, REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new Notification.Builder(this)
        .setContentTitle(title)
        .setContentText(text)
        .setSmallIcon(icon)
        .setContentIntent(pendingIntent)
        .build();
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容