首页 > 解决方案 > 还必须在前台启动 Android 子服务吗?

问题描述

在我的 Android 应用程序中,我记录了很多东西,比如 GPS、气压、蓝牙传感器。有一个“超级”服务在前台启动:

Intent intent = new Intent(context, DataCollectorService.class);
ContextCompat.startForegroundService(context, intent);

该服务本身必须启动许多子服务,如 GPS 记录、蓝牙传感器记录等。该服务会创建一个通知:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    // . . . 
    Notification notification = new NotificationCompat.Builder(this, channelId)
            // . . .
            .build();

    startForeground(NOTIFICATION_ID, notification);

    mHandler.postDelayed(this::startChildServices, 100);
    return START_STICKY;
}

private void startChildServices() {
    // . . .
    if (gpsEnabled) {
        Intent intent = new Intent(this, GpsTrackingService.class);
        bindService(intent, mGpsServiceConnection, Context.BIND_AUTO_CREATE);
        startService(intent);
    }
    if (isPressureEnabled) {
        Intent intent = new Intent(this, PressureService.class);
        bindService(intent, pressureConnection, Context.BIND_AUTO_CREATE);
        startService(intent);
    }
    // . . .
}

一切正常,但极少数用户会遇到这样的崩溃:

android.app.RemoteServiceException: Context.startForegroundService() 然后没有调用 Service.startForeground()

实际上,如您所见,我在前台启动了“超级”服务。

我是否也必须在前台启动子服务?

显然,我不想在用户状态栏中有 3-7 个通知图标。

标签: androidandroid-serviceandroid-permissions

解决方案


推荐阅读