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

家住魔仙堡 提交于 2019-12-02 05:57:28

Step #1: Set project.ext.supportLibVersion to 26.1.0 or higher

Step #2: Note that you are now getting deprecation warnings on all your new NotificationCompat.Builder() calls

Step #3: Define a NotificationChannel (if you have not defined it on some previous run of the app)

Step #4: Pass the channel ID to the NotificationCompat.Builder constructor

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!