美文网首页通知栏
Android发送通知(Notification)

Android发送通知(Notification)

作者: 好学人 | 来源:发表于2019-09-25 22:01 被阅读0次

    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();
    

    相关文章

      网友评论

        本文标题:Android发送通知(Notification)

        本文链接:https://www.haomeiwen.com/subject/puwwuctx.html