欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

解决StartForeground Bad Notification Error错误

程序员文章站 2022-07-14 16:38:13
...

Android8.0的Notification添加了用户渠道,使得Android7.0的通知不在适配8.0。新设计让用户有了更多的自主选择权利,更人性化,应该及时学会新变化,跟上新内容。

错误信息

  • 今天打开Android studio,运行以前的音乐项目,当我在手机上进行调试的时候出现了如下错误:

解决StartForeground Bad Notification Error错误

  • 经过上网搜索,得知Android 8.0 对于Notification有了新的设计,具体原因见下图:

解决StartForeground Bad Notification Error错误

解决办法

  • 在Android8.0后 需要给notification设置一个channelid,这里有官方的代码。具体的做法就是创建一个NotificationChannel,修改后的代码如下:

    解决StartForeground Bad Notification Error错误

  • 代码改动的地方有两处,下面是改动的代码:

···

      if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
        notificationChannel = new NotificationChannel(CHANNEL_ONE_ID,
                CHANNEL_ONE_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);


        PendingIntent contentIntents = PendingIntent.getActivity(this, 0, intents, 0);
        //新增setChannelId()方法--------------------------------------
        mbuilder = new Notification.Builder(this).setChannelId(CHANNEL_ONE_ID);
        mRemoteViews = new RemoteViews(getPackageName(), R.layout.notification);
        mbuilder.setContent(mRemoteViews)
                .setContentIntent(contentIntents)
                .setSmallIcon(R.mipmap.music)
                .setContentText(name);


        mRemoteViews.setTextViewText(R.id.notification_name, musiclist.get(curposition).getTitle());
        mRemoteViews.setTextViewText(R.id.notification_arti, musiclist.get(curposition).getArtist());

        //为intent添加play属性
        Intent intentnext = new Intent("next");
        PendingIntent pintentnext = PendingIntent.getBroadcast(this, 0, intentnext, 0);
        mRemoteViews.setOnClickPendingIntent(R.id.btn_custom_next, pintentnext);

        Intent intentplay = new Intent("play");
        PendingIntent pintentplay = PendingIntent.getBroadcast(this, 0, intentplay, 0);
        mRemoteViews.setOnClickPendingIntent(R.id.btn_custom_play, pintentplay);

        Intent intentpause = new Intent("pause");
        PendingIntent pintentpause = PendingIntent.getBroadcast(this, 0, intentpause, 0);
        mRemoteViews.setOnClickPendingIntent(R.id.btn_custom_pause, pintentpause);

        Notification notify = mbuilder.build();
        startForeground(1, notify);
    }

···