A notification of the foreground service doesn't show on Android 8.+

后端 未结 2 931
傲寒
傲寒 2021-01-23 17:48

My foreground service doesn\'t show a notification when it works on Android Oreo.

It works perfectly on Android versions from 15 to 25. When I do targetSdkVersion<

2条回答
  •  有刺的猬
    2021-01-23 18:29

    I've just changed my method prepareNotification() in SoundService.java from:

        private Notification prepareNotification() {
                Intent notificationIntent = new Intent(this, MainActivity.class);
                notificationIntent.setAction(MusicConstants.ACTION.MAIN_ACTION);
                //...
                NotificationCompat.Builder lNotificationBuilder = new NotificationCompat.Builder(this);
               //...
    

    to:

        private Notification prepareNotification() {
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O &&
                        mNotificationManager.getNotificationChannel(FOREGROUND_CHANNEL_ID) == null) {
                    // The user-visible name of the channel.
                    CharSequence name = getString(R.string.text_value_radio_notification);
                    int importance = NotificationManager.IMPORTANCE_DEFAULT;
                    NotificationChannel mChannel = new NotificationChannel(FOREGROUND_CHANNEL_ID, name, importance);
                    mChannel.enableVibration(false);
                    mNotificationManager.createNotificationChannel(mChannel);
                }
                Intent notificationIntent = new Intent(this, MainActivity.class);
                notificationIntent.setAction(MusicConstants.ACTION.MAIN_ACTION);
               //...
               NotificationCompat.Builder lNotificationBuilder;
               if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
               lNotificationBuilder = new NotificationCompat.Builder(this, FOREGROUND_CHANNEL_ID);
               } else {
               lNotificationBuilder = new NotificationCompat.Builder(this);
               }
               //...
    

    You can see the full difference here.

提交回复
热议问题