Service.startForeground() 不允许,因为 Android 14 上的 mAllowStartForeground false

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

自 Android 14 起,我的应用程序出现此错误。我通过尝试在设备关闭电源(仅屏幕)时从 android Studio 启动应用程序来成功重现该错误。

这是我的代码的描述: 我使用前台服务订阅定期 GPS 定位

        <service
            android:name=".Service.MyLocationService"
            android:foregroundServiceType="location"
            android:label="Location receiver" />

我在主活动的 onResume() 中启动一次服务。

 locationIntent = new Intent(this, MyLocationService.class);
 startForegroundService(locationIntent);

我确保在其他地方授予这些权限:

ACCESS_FINE_LOCATION & ACCESS_COARSE_LOCATION

我的服务是这样的:

public class MyLocationService extends Service {

    private Notification myNotification = ...;

    private FusedLocationProviderClient mFusedLocationClient;

    public MyLocationService() {
        super();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForeground(1, myNotification);
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        initFunction(this);
        return Service.START_REDELIVER_INTENT;
    }

    @Override
    public void onDestroy() {
        destroyFunction();
        super.onDestroy();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    public void initFunction(Context context) {

        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(context);

        mLocationCallback = new LocationCallback() {
            @Override
            public void onLocationResult(LocationResult locationResult) {
                super.onLocationResult(locationResult);
                if (locationResult == null) {
                    return;
                }
       
                // Here I use the received location

            }
        };


        mLocationRequest = new LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, 1000)
                .setWaitForAccurateLocation(true)
                .setMinUpdateIntervalMillis(1000)
                .setMaxUpdateDelayMillis(1000)
                .build();

        mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());

    }

   private void destroyFunction() {
        if (mFusedLocationClient != null) {
            mFusedLocationClient.removeLocationUpdates(mLocationCallback);
            mFusedLocationClient = null;
        }
    }

}

我尝试过用工人代替服务,但没有成功。 我现在应该如何继续使用 Android 14?有想法吗?

java android background location foreground-service
1个回答
0
投票

我已经用这种方式更新了我的代码,但没有任何好处

@Override
public void onCreate() {
    super.onCreate();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        startForeground(1, myNotification,

ServiceInfo.FOREGROUND_SERVICE_TYPE_LOCATION); } 否则如果 (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { startForeground(1, myNotification); } }

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