当启动前台服务时,Android 9和Android 10的RemoteServiceException异常。

问题描述 投票:0回答:1

我启动了一个前台服务,在Android 8及以下版本中可以正常工作;但在Android 9和Android 10中,它给出了RemoteServiceException。

我在onCreate和onStartCommand中调用了startMyForegroundService()。

private void startMyForegroundService() {
    try {
        //prevent 5 seconds Context.startForegroundService() did not then call Service.startForeground()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            String CHANNEL_ID = "my_service";
            String CHANNEL_NAME = "My Background Service";

            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_NONE);
            channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);

            NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            assert manager != null;
            manager.createNotificationChannel(channel);

            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, CHANNEL_ID);
            Notification notification = notificationBuilder.setOngoing(true)
                    .setPriority(NotificationManager.IMPORTANCE_HIGH)
                    .setCategory(Notification.CATEGORY_SERVICE)
                    .build();
            startForeground(2, notification);
        } else {
            startForeground(1, new Notification());
        }
    } catch (Exception ex) {
        //Crashlytics.logException(ex);
        Log.e(StandOutWindow.class.getName(), "Service manager can't start service ");
    }
}

异常

Fatal Exception: android.app.RemoteServiceException: Bad notification for startForeground: java.lang.RuntimeException: invalid channel for service notification: Notification(channel=null pri=0 contentView=null vibrate=null sound=null tick defaults=0x0 flags=0x60 color=0x00000000 vis=SECRET internalType=0 internalPriority=0 internalGroupPriority=0 internalFlag=0)
   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1965)
   at android.os.Handler.dispatchMessage(Handler.java:106)
   at android.os.Looper.loop(Looper.java:224)
   at android.app.ActivityThread.main(ActivityThread.java:7081)
   at java.lang.reflect.Method.invoke(Method.java)
   at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:536)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:928)

如果你需要更多信息,请告诉我。

android service android-9.0-pie android-10.0 foreground-service
1个回答
0
投票

原来还有一个创建通知的方法,所以我只要在创建通知之前先创建通道就可以了。

© www.soinside.com 2019 - 2024. All rights reserved.