通知没有出现?

时间:2018-01-15 11:38:24

标签: android android-notifications

以下是我的通知构建器 func:

public class NotificationHelper {

final static String CHANNEL_ID = "MY_CHANNEL_ID";
final static String CHANNEL_NAME = "MY_CHANNEL_NAME";


public static Notification buildNotificationInstance(Context ctx, String title, String message) {

    Notification notification;
    NotificationCompat.Builder mBuilder;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
        mBuilder = new NotificationCompat.Builder(ctx, CHANNEL_ID);
    } else {
        mBuilder = new NotificationCompat.Builder(ctx);
    }

    mBuilder.setContentTitle(title)
            .setContentText(message)
            .setSmallIcon(R.drawable.ic_android_black_24dp);

    Bitmap bm = BitmapFactory.decodeResource(ctx.getResources(), R.mipmap.ic_launcher);
    mBuilder.setLargeIcon(bm);


    notification = mBuilder.build();


    return notification;
    }
}

尝试在活动的onCreate()上显示通知

Notification notification = NotificationHelper.buildNotificationInstance(this, "title", "message");
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(1, notification);

通知未显示。我做错了什么?

我在 Android 8

上进行测试

2 个答案:

答案 0 :(得分:1)

你必须为notificationBuilder添加pendingIntent,如下所示:

PendingIntent pendingIntent = PendingIntent.getActivity(this, 0/*Request code*/, intent, PendingIntent.FLAG_ONE_SHOT);

mBuilder.setContentTitle(title)
        .setContentText(message)
        .setSmallIcon(R.drawable.ic_android_black_24dp)
        .setContentIntent(pendingIntent);

答案 1 :(得分:1)

您必须为其工作创建通知渠道: 试试这个:

 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
        mBuilder = new NotificationCompat.Builder(ctx, CHANNEL_ID);

        notificationChannel.setDescription("description");
        notificationChannel.enableLights(true);
        NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(NOTIFICATION_SERVICE);
        notificationManager.createNotificationChannel(notificationChannel);
    }