android.app.RemoteServiceException: Bad notification for startForeground

元气小坏坏 提交于 2019-12-27 01:16:03

【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>

错误提示:

android.app.RemoteServiceException: Bad notification for startForeground: java.lang.RuntimeException: invalid channel for service notification: Notification(channel=null 

8.0后要加上channel来区分通知,故需要改为如下的写法:

/**
     * 设置服务在前台可见
     */
    private void startForeground(){
        /**
         * 通知栏点击跳转的intent
         */
        PendingIntent pendingIntent = PendingIntent.getActivity(this,0, new Intent(this, WelcomeActivity.class), PendingIntent.FLAG_CANCEL_CURRENT);

        /**
         * 创建Notification
         */
        NotificationChannel notificationChannel;
        Notification notification;
        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.O){
            notificationChannel= new NotificationChannel(CHANNEL_ID,
                    CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
            notificationChannel.enableLights(true);
            notificationChannel.setLightColor(Color.RED);
            notificationChannel.setShowBadge(true);
            notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
            NotificationManager manager= (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            manager.createNotificationChannel(notificationChannel);

            notification = new NotificationCompat.Builder(this, CHANNEL_ID)
                    .setContentTitle(mMusicModel.getName())
                    .setContentText(mMusicModel.getAuthor())
                    .setSmallIcon(R.mipmap.logo)
                    .setContentIntent(pendingIntent)
                    .build();
        }else{
            notification = new Notification.Builder(this)
                    .setContentTitle(mMusicModel.getName())
                    .setContentText(mMusicModel.getAuthor())
                    .setSmallIcon(R.mipmap.logo)
                    .setContentIntent(pendingIntent)
                    .build();
        }

        /**
         * 设置notification在前台展示
         */
        startForeground(NOTIFICATION_ID, notification);
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!