2

我从主要活动开始服务,例如;-

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

MyLocationService 类看起来像:-

public class MyLocationService extends Service implements
        LocationListener,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener {
    private static final String TAG = MyLocationService.class.getSimpleName();
    public static Location mCurrentLocation;
    LocationRequest mLocationRequest;
    GoogleApiClient mGoogleApiClient;
    @Override
    public void onCreate() {
        Log.e(TAG, "onCreate: ");
        initiateGooglePlayService();
    }
    public void initiateGooglePlayService() {
        Log.e(TAG, "initiateGooglePlayService: ");
        if (isGooglePlayServicesAvailable()) {
            mLocationRequest = new LocationRequest();
            mLocationRequest.setInterval(5000);
            mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
            mLocationRequest.setSmallestDisplacement(10.0f);
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addApi(LocationServices.API)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .build();
            mGoogleApiClient.connect();
        }
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e(TAG, "onStartCommand: ");
        return super.onStartCommand(intent, flags, startId);
    }
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.e(TAG, "onBind: ");
        return null;
    }
    private boolean isGooglePlayServicesAvailable() {
        Log.e(TAG, "isGooglePlayServicesAvailable: ");
        int status = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(getApplicationContext());
        return ConnectionResult.SUCCESS == status;
    }
    @Override
    public void onConnected(Bundle bundle) {
        Log.e(TAG, "onConnected: ");
        startLocationUpdates();
    }
    @Override
    public void onConnectionSuspended(int i) {
        Log.e(TAG, "onConnectionSuspended: ");
    }
    protected void startLocationUpdates() {
        Log.e(TAG, "startLocationUpdates: ");
        try {
            PendingResult<Status> pendingResult;
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

                return;
            }
            pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(
                    mGoogleApiClient, mLocationRequest, this);
        } catch (IllegalStateException ignored) {
        }
    }
    @Override
    public void onLocationChanged(Location location) {
        Log.e(TAG, "onLocationChanged: " + location.getLongitude());
        if (mGoogleApiClient.isConnected()) {
            mCurrentLocation = location;
            Intent intent = new Intent("GPSLocationUpdates");
            intent.putExtra("location", location);
         LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
            Toast.makeText(this, "location", Toast.LENGTH_LONG).show();
        }
    }
    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        Log.e(TAG, "onConnectionFailed: ");
    }
}

我从不在任何地方停止服务。

但我仍然无法控制onLocationChange()

我的动机是,我需要连续定位来做一些后台操作。它有时在棒棒糖中起作用。但它在 Marshmallow 和 nougat 甚至 kitkat 中也不起作用。我搜索但无法得到正确的想法。请让我知道,我哪里出错了。接受任何建议。

我正在使用以下依赖项作为位置;-

 compile 'com.google.android.gms:play-services-location:9.6.1'
4

2 回答 2

2

您可以使用HyperTrack SDK 在后台获取位置更新。在此处了解更多有关 SDK在不同条件下的可靠性的信息。

首先设置SDK

设置 SDK 后,您只需设置回调以接收位置更新。

HyperTrack.setCallback(new HyperTrackEventCallback() {
@Override
public void onEvent ( @NonNull final HyperTrackEvent event){
    switch (event.getEventType()) {
        case HyperTrackEvent.EventType.LOCATION_CHANGED_EVENT:
            Log.d(TAG, "onEvent: Location Changed");
            HyperTrackLocation hyperTrackLocation = event.getLocation();
            LatLng latLng = hyperTrackLocation.getLatLng();
            updateCurrentLocationMarker(event.getLocation());
            break;
    }
}
}

(免责声明:我在 HyperTrack 工作。)

于 2017-09-20T07:09:51.900 回答
1
/**Check out my Github post i did the same for Taxi clone**/

Link ---> https://github.com/yash786agg/GPS/

Note: Remember to remove or comment the below mentioned code if you want the latitude 
and latitude even when the application is in background.

    if(networkUtilObj != null)
    {
        networkUtilObj.disconnectGoogleApiClient();
    }
于 2017-08-31T10:20:10.760 回答