通知未显示在Android上

时间:2019-07-14 11:16:01

标签: android

我有一个透明的活动,总是在打开通知时创建一个通知,但是在测试时,它仅显示Toast,而不显示通知。这是该活动的代码:

super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        Toast toast = Toast.makeText(MainActivity.this, "The screen is now always on", Toast.LENGTH_SHORT);
        toast.show();
        Intent intent = new Intent(this, thoat.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "M_CH_ID");
        notificationBuilder.setAutoCancel(true)
                .setDefaults(Notification.DEFAULT_ALL)
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.drawable.lightbulb_icon)
                .setContentTitle("The screen is now always on!")
                .setContentText("Tap here to disable this program")
                .setContentIntent(pendingIntent)
                .setAutoCancel(true)
        .build();
        NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(0, notificationBuilder.build());

我做错了什么?

2 个答案:

答案 0 :(得分:0)

替换

 Intent intent = new Intent(this, thoat.class);

 Intent intent = new Intent();

答案 1 :(得分:0)

检查此方法:

public void showNotification(Context context, String title, String body, Intent intent) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

int notificationId = 1;
String channelId = "channel-01";
String channelName = "Channel Name";
int importance = NotificationManager.IMPORTANCE_HIGH;

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
    NotificationChannel mChannel = new NotificationChannel(
            channelId, channelName, importance);
    notificationManager.createNotificationChannel(mChannel);
}

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, channelId)
        .setSmallIcon(R.mipmap.ic_launcher)
        .setContentTitle(title)
        .setContentText(body);

TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addNextIntent(intent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(
        0,
        PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);

notificationManager.notify(notificationId, mBuilder.build());

}