Error de inicio de servicio: Context.startForegroundService() no llamó a Service.startForeground():

AndroidRuntime: android.app.RemoteServiceException: Context.startForegroundService() no llamó a Service.startForeground():

Por primera vez, use startService(intent) en Launcher; inicie el servicio de otras aplicaciones, para que no pueda ingresar al servicio y
aparecerá

APP in background in null uid

Android 8.0 realizó los siguientes cambios en funciones específicas:
Para las aplicaciones de Android 8.0, si se usa la función startService() sin permitirle crear un servicio en segundo plano, la función arrojará un error IllegalStateException.
La solución que uso es:
cambie startService() a startForegroundService() para iniciar, y llame a startForegroundService() en el código del servidor; esto es para convertir el servicio de fondo en un servicio de primer plano e iniciarlo .
Modificar el código en Launcher

    private void startNmvSideBarService() {
    
    
        ComponentName chatService = new ComponentName("启动app的包名",
                "启动app的包名.启动的服务类");
        Intent intent = new Intent();
        intent.setComponent(chatService);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    
    
            startForegroundService(intent);
        }
        else {
    
    
            startService(intent);
        }
    }

Vale la pena señalar aquí que
Android 8.0 tiene una complicación: el sistema no permite que las aplicaciones en segundo plano creen servicios en segundo plano. Por lo tanto, Android 8.0 presenta un método completamente nuevo, Context.startForegroundService(), para iniciar un nuevo servicio en primer plano.
Después de que el sistema crea un servicio, las aplicaciones tienen 5 segundos para llamar al método startForeground() del servicio para mostrar una notificación visible para el usuario para el nuevo servicio. Si la aplicación no llama a startForeground() dentro de este límite de tiempo, el sistema detiene el servicio y declara la aplicación como ANR.
Pero la llamada actual: context.startForegroundService(intent) informa el siguiente ANR, y el documento startForegroundService() establece que se debe llamar a startForeground() después de que se inicie el servicio.
En resumen, si usa
startForegroundService, debe usar startForeground() , de lo contrario, se informará el siguiente error

AndroidRuntime: android.app.RemoteServiceException: Context.startForegroundService()
 did not then call Service.startForeground():

Hay muchos métodos en Internet, y muchos de ellos son inútiles.Finalmente, encontré un blog y usé su código directamente, para que no se bloquee después de iniciar el servicio.
1. Agregue el archivo xml

    <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>

2. Agregue el siguiente código a OnCreate en el servicio iniciado

        String ID = "com.xxxx.xxxx";	//这里的id里面输入自己的项目的包的路径
        String NAME = "LEFTBAR";
        Intent intent = new Intent(被启动服务名称.this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
        NotificationCompat.Builder notification; //创建服务对象
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    
    
            NotificationChannel channel = new NotificationChannel(ID, NAME, manager.IMPORTANCE_HIGH);
            channel.enableLights(true);
            channel.setShowBadge(true);
            channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
            manager.createNotificationChannel(channel);
            notification = new NotificationCompat.Builder(SideToolbarService.this).setChannelId(ID);
        } else {
    
    
            notification = new NotificationCompat.Builder(SideToolbarService.this);
        }
        notification.setContentTitle("标题")
                .setContentText("内容")
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.mipmap.ic_launcher)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
                .setContentIntent(pendingIntent)
                .build();
        Notification notification1 = notification.build();
        startForeground(1,notification1);//这个就是之前说的startForeground

En cuanto a por qué está escrito así, no lo sé, de todos modos, el programa y el programador pueden funcionar juntos.

Guess you like

Origin blog.csdn.net/weixin_46362658/article/details/127414362