Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android

Patrick Coyne
Patrick Coyne
5,026 Points

Notifications on Android 8.0 (Oreo)

I am wondering how to update Notification to be used on Android 8.0 and above, they do not show the notifications in the video. For when putting them into the foreground on the musicMachine app

Michael Nock
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Michael Nock
Android Development Techdegree Graduate 16,018 Points

On Android 8.0 you need to create a NotificationChannel and then add the ChannelId to your Notification Builder object. You'll need to create the NotificationChannel with the NotificationManager's (getSystemService(Context.NOTIFICATION_SERVICE)) createNotificationChannel method.

Here's an example of what you could do:

public class PlayerService extends Service {
    public static final String NOTIFICATION_CHANNEL_ID = "1337";
    public static final String NOTIFICATION_CHANNEL_NAME = "music-player";
//...
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Notification.Builder notificationBuilder = new Notification.Builder(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel notificationChannel =
                    new NotificationChannel(
                            NOTIFICATION_CHANNEL_ID,
                            NOTIFICATION_CHANNEL_NAME,
                            NotificationManager.IMPORTANCE_LOW);
            notificationChannel.enableLights(true);
            notificationChannel.setLightColor(Color.BLUE);
            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.createNotificationChannel(notificationChannel);
            notificationBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
        }
        notificationBuilder.setLights(Color.BLUE, 1000, 500);
        notificationBuilder.setVibrate(new long[]{0, 300, 300, 300});
        notificationBuilder.setSmallIcon(R.mipmap.ic_launcher);
        Notification notification = notificationBuilder.build();
        startForeground(11, notification);

        mediaPlayer.setOnCompletionListener(mediaPlayer -> {
            stopSelf();
            stopForeground(true);
        });
        return Service.START_NOT_STICKY;
    }
}