即使从最近的抽屉中杀死了应用程序,也可以使用服

时间:2017-08-31 09:46:38

标签: android android-service google-geolocation google-location-services

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

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()

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

我正在使用以下依赖关系来定位; -

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

2 个答案:

答案 0 :(得分:2)

您可以使用HyperTrack SDK在后台获取位置更新。在不同条件下更深入地了解SDK here的可靠性。

首先Setup SDK

设置SDK后,您只需将Callback设置为接收位置更新。

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工作。)

答案 1 :(得分: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();
    }