Learn about Android (new NotificationCompat.Builder is out of date)

Posted by phpfolk2003 on Thu, 31 Oct 2019 08:53:54 +0100

Today, when learning the notification function of android, we found that

new NotificationCompat.Builder(MainActivity.this)

When running the app, it is found that the notification effect is not normal, but an error is reported.

After searching on the Internet, we know the solution

After Android O, this method is replaced by the following methods:

NotificationCompat.Builder(Context context, String channelId)

The modified code is as follows:

NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification notification = new NotificationCompat.Builder(MainActivity.this, "001")
        .setContentTitle("This is content title")
        .setContentText("This is content text")
        .setWhen(System.currentTimeMillis())
        .setSmallIcon(R.mipmap.ic_launcher)
        .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
        .build();
notificationManager.notify(1, notification);

Where the first parameter is context and the second parameter represents channelId. At this time, - no, but when the app is running, it still reports an error.

Later, I found that I didn't create a channel. The final code is as follows:

NotificationChannel notificationChannel = null;
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
    notificationChannel = new NotificationChannel("001", "channel_name", NotificationManager.IMPORTANCE_HIGH);
    notificationManager.createNotificationChannel(notificationChannel);
}
Notification notification = new NotificationCompat.Builder(MainActivity.this, "001")
        .setContentTitle("This is content title")
        .setContentText("This is content text")
        .setWhen(System.currentTimeMillis())
        .setSmallIcon(R.mipmap.ic_launcher)
        .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
        .build();
notificationManager.notify(1, notification);

Finally, the app runs normally

Topics: Android