Can stop updating location, Android service

I am trying to create a route tracking application. it should track the location even if the app is in the background. so I created a service and added the code for that service. Below is my code. but there is one problem. I am starting a service from my main activity.

public void startTracking(View view) {
    startService(new Intent(MainActivity.this, LocationIntentService.class));
}

public void stopTracking(View view) {
    stopService(new Intent(MainActivity.this, LocationIntentService.class));
}

      

Will start the service and the locations are inserted into the local database. But I cannot stop these services. When I quit using the above code, it still tracks the location. How to stop updating a location.

public class LocationIntentService extends IntentService implements LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {

    private static final String TAG = LocationIntentService.class.getSimpleName();
    private static final long INTERVAL = 1000 * 10;
    private static final long FASTEST_INTERVAL = 1000 * 5;
    private static int DISPLACEMENT = 10;

    LocationRequest mLocationRequest;
    GoogleApiClient mGoogleApiClient;
    Location mLastLocation;
    DBAdapter dbAdapter;

    public LocationIntentService() {
        super("LocationIntentService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Log.e(TAG, " ***** Service on handled");
        if (isGooglePlayServicesAvailable()) {
            createLocationRequest();
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addApi(LocationServices.API)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .build();
            mGoogleApiClient.connect();
        }
    }

    @Override
    public void onConnected(Bundle bundle) {
        Log.e(TAG, " ***** Service on connected");
        startLocationUpdates();
        openDB();
    }

    @Override
    public void onConnectionSuspended(int i) {
        Log.e(TAG, " ***** Service on suspended");
        mGoogleApiClient.connect();
    }

    @Override
    public void onLocationChanged(Location location) {
        Log.e(TAG, "Location changed");
        mLastLocation = location;

        String latitude = String.valueOf(mLastLocation.getLatitude());
        String longitude = String.valueOf(mLastLocation.getLongitude());
        Log.e(TAG, " ##### Got new location"+ latitude+ longitude);

        Time today = new Time(Time.getCurrentTimezone());
        today.setToNow();
        String timestamp = today.format("%Y-%m-%d %H:%M:%S");

        dbAdapter.insertRow(latitude, longitude, timestamp);
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        Log.e(TAG, "Connection failed: ConnectionResult.getErrorCode() = "
                + connectionResult.getErrorCode());
    }

    @Override
    public void onDestroy() {
        Log.e(TAG, "Service is Destroying...");
        super.onDestroy();
        if (mGoogleApiClient.isConnected()) {
            stopLocationUpdates();
            mGoogleApiClient.disconnect();
        }
        closeDB();
    }

    protected void stopLocationUpdates() {
        Log.d(TAG, "Location update stoping...");
        LocationServices.FusedLocationApi.removeLocationUpdates(
                mGoogleApiClient, this);
    }

    protected void startLocationUpdates() {
        Log.d(TAG, "Location update starting...");
        LocationServices.FusedLocationApi.requestLocationUpdates(
                mGoogleApiClient, mLocationRequest, this);

    }

    private void openDB() {
        dbAdapter = new DBAdapter(this);
        dbAdapter.open();
    }

    private void closeDB() {
        dbAdapter = new DBAdapter(this);
        dbAdapter.close();
    }

    protected void createLocationRequest() {
        Log.e(TAG, " ***** Creating location request");
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(INTERVAL);
        mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
    }

    private boolean isGooglePlayServicesAvailable() {
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        if (ConnectionResult.SUCCESS == status) {
            return true;
        } else {
            Log.e(TAG, " ***** Update google play service ");
            return false;
        }
    }
}

      

+3


source to share


4 answers


The reason it doesn't work for you is because you are using IntentService

, so the call stopService()

will not result in a call onDestroy()

, presumably because it was already called after completion onHandleIntent()

. No need to ever call stopService()

on IntentService

see here .

It looks like you should just use Service

instead IntentService

. This way when you call stopService()

it will trigger onDestroy()

and unregister location updates as you expect.

The only other change you would need to make is to override onStartCommand()

instead onHandleIntent()

.



You will have class extension Service

instead IntentService

, and then move your code to register location updates to onStartCommand

:

 @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e(TAG, " ***** Service on start command");
        if (isGooglePlayServicesAvailable()) {
            createLocationRequest();
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addApi(LocationServices.API)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .build();
            mGoogleApiClient.connect();
        }
        return Service.START_STICKY;
    }

      

That way, you can still call startService()

and stopService()

, and it should work as you expect.

+3


source


LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);

      



+1


source


call the stopLocationUpdates () method in stopService ()

0


source


When you stop your services. Then this line is called in LocationIntentService.class .

locationManager.removeUpdates(this);

      

0


source







All Articles