[LocationCallBack当应用程序在后台时未在服务上调用

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

当应用程序在后台甚至被杀死时,我试图获取我当前的gps位置。因此,我创建了一个名为MyBackgroundLocationService.class的服务类。

public class MyBackgroundLocationService extends Service {
private static final String TAG = MyBackgroundLocationService.class.getSimpleName();
private FusedLocationProviderClient mLocationClient;
LocationCallback mLocationCallBack;
public MyBackgroundLocationService() {
}

@Override
public void onCreate() {
    super.onCreate();
    mLocationClient = LocationServices.getFusedLocationProviderClient(getApplicationContext());
    mLocationCallBack = new LocationCallback(){
        @Override
        public void onLocationResult(LocationResult locationResult) {
            if (locationResult == null){
                Log.d(TAG, "onLocationResult: is null");
                return;
            }

            Log.d(TAG, "onLocationResult: "+locationResult.getLocations().get(0).getLatitude() + "/" + locationResult.getLocations().get(0).getLongitude());
        }
    };
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.d(TAG, "onStartCommand: ");
    getLocationUpdates();
    return START_STICKY;
}

private void getLocationUpdates() {
    final LocationRequest locationRequest = LocationRequest.create();

    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    locationRequest.setInterval(1800);
    locationRequest.setFastestInterval(16);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            stopSelf();
        }
    }
    mLocationClient.requestLocationUpdates(locationRequest, mLocationCallBack, Looper.myLooper());
}

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

@Override
public void onDestroy() {
    super.onDestroy();
    Log.d(TAG, "onDestroyCommand: ");
   // mLocationClient.removeLocationUpdates(mLocationCallBack);
}

}

我像这样从我的mainClass调用了该服务:

Intent intent = new Intent(MapsActivity.this,MyBackgroundLocationService.class);
            startService(intent);

这是清单文件中声明服务的方式:

<service
        android:name=".MyBackgroundLocationService"
        android:enabled="true"
        android:exported="false"
        />

所以问题出在我关闭应用程序的任何地方,LocationCallBack停止了,我该怎么办?

当应用程序在后台甚至被杀死时,我试图获取我当前的gps位置。因此,我创建了一个名为MyBackgroundLocationService.class public class的服务类...

android service android-location
1个回答
0
投票

您需要阅读有关使用android 8及更高版本中的后台服务或警报的政策的android官方文档,并在此限制下适应您的应用。

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