Android发送通知(Notification)

Android 8.0(<API 26)

// 创建通知(标题、内容、图标)
Notification notification = new Notification.Builder(this)
        .setContentTitle("通知标题")
        .setContentText("通知内容")
        .setSmallIcon(R.mipmap.ic_launcher)
        .build();
// 创建通知管理器
NotificationManager manager = (NotificationManager) context
        .getSystemService(Context.NOTIFICATION_SERVICE);
// 发送通知
manager.notify(1, notification);

Android 8.0(≥API 26)

Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
// 1. 创建一个通知(必须设置channelId)
Context context = getApplicationContext();
String channelId = "ChannelId"; // 通知渠道
Notification notification = new Notification.Builder(context)
        .setChannelId(channelId) 
        .setSmallIcon(R.mipmap.icon_bill_64x64)
        .setContentTitle("通知标题")
        .setContentText("通知内容")
        .build();
// 2. 获取系统的通知管理器(必须设置channelId)
NotificationManager notificationManager = (NotificationManager) context
        .getSystemService(NOTIFICATION_SERVICE);
NotificationChannel channel = new NotificationChannel(
        channelId,
        "通知的渠道名称",
        NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
// 3. 发送通知(Notification与NotificationManager的channelId必须对应)
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();
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容