0

I am using GoogleApiClient to get the Location updates for every ten seconds and it is working properly as expected But i want my application to do the same i.e,to send the location updates even when it is minimized or Back button is pressed which is not working.For Back Button i have used following code.

@Override
public void onBackPressed() {
    moveTaskToBack(true);

}
AGM
  • 83
  • 1
  • 2
  • 12

1 Answers1

1

Try to use this helper class to start location updates :

Edited :

import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;

public class LocationHandler implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
    private static final String TAG = LocationHandler.class.getSimpleName();
    private Context mContext;
    public GoogleApiClient mGoogleApiClient;
    private LocationRequest mLocationRequest;
    private Location mCurrentLocation;
    private Handler handler;
    public boolean isLocationAvailable = false;

    public LocationHandler(Context context, Handler mHandler) {
        this.mContext = context;
        this.handler = mHandler;
        buildGoogleApiClient();
    }

    @Override
    public void onConnected(Bundle bundle) {
        LocationManager locationManager = (LocationManager)
                this.mContext.getSystemService(Context.LOCATION_SERVICE);
        isLocationAvailable = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) &&
                locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (mCurrentLocation == null) {
            mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        }
        isLocationAvailable = true;
        startLocationUpdates();
        this.handler.sendEmptyMessage(0);
    }

    @Override
    public void onConnectionSuspended(int i) {
        Log.d(TAG, "onConnectionSuspended");
        mGoogleApiClient.connect();
    }

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


    @Override
    public void onLocationChanged(Location location) {
        Log.d(TAG, "onLocationChanged = " + location.getLatitude());
        mCurrentLocation = location;
    }

    /**
     * To create location request
     */
    public void createLocationRequest() {
        Log.d(TAG, "createLocationRequest");
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(60 * 1000);
        mLocationRequest.setFastestInterval(60 * 1000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
    }

    /**
     * To build google client
     */
    public synchronized void buildGoogleApiClient() {
        Log.d(TAG, "buildGoogleApiClient");
        mGoogleApiClient = new GoogleApiClient.Builder(this.mContext)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        createLocationRequest();
        mGoogleApiClient.connect();
    }

    /**
     * To start location updates
     */
    public void startLocationUpdates() {
        Log.d(TAG, "startLocationUpdates");
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    }

    /**
     * To stop location updates
     */
    public void stopLocationUpdates() {
        Log.d(TAG, "stopLocationUpdates");
        LocationServices.FusedLocationApi.removeLocationUpdates(
                mGoogleApiClient, this);
    }

    /**
     * To get current location
     *
     * @return A location object
     */
    public Location getCurrentLocation() {
        return mCurrentLocation;
    }
}

In your activity do :

  1. Check for internet connection.
  2. Check for GPS is enabled or not.
  3. Start location updates if both of above are true.

Like this :

Activity where we get location change updates :

import android.app.Activity;
import android.content.Context;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import java.lang.ref.WeakReference;


public class MainActivity extends Activity {

    private LocationHandler locationUtility;
    private LocationManager mLocationManager = null;
    private IncomingHandler incomingHandler;

    /**
     * Handler of incoming messages from clients.
     */
    private static class IncomingHandler extends Handler {
        private WeakReference<MainActivity> mainActivityWeakReference;

        public IncomingHandler(MainActivity mainActivity) {
            mainActivityWeakReference = new WeakReference<>(mainActivity);
        }

        @Override
        public void handleMessage(Message message) {
            if (mainActivityWeakReference != null) {
                MainActivity mainActivity = mainActivityWeakReference.get();
                switch (message.what) {
                    case 0:

                        boolean isConnected = // check internet is connected
                        boolean isGPSEnabled = mainActivity.mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
                        boolean isNetworkEnabled = mainActivity.mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

                        if (!isConnected) {
                            // show alert or toast
                        }
                        if (!(isGPSEnabled && isNetworkEnabled)) {
                            // show alert or toast
                        }
                        if (mainActivity.locationUtility.mGoogleApiClient.isConnected()) {
                            mainActivity.locationUtility.startLocationUpdates(); // start updates
                        }
                        break;
                }
            }
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        incomingHandler = new IncomingHandler(this);
        locationUtility = new LocationHandler(MainActivity.this, incomingHandler);
        mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    }

}

When you want to stop updates use :

if (locationUtility.mGoogleApiClient.isConnected()) {
            locationUtility.stopLocationUpdates();
        }

This will update location even though your activity is paused unless it destroyed.

Also not to forget adding following permission in Manifest.xml :

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

Thanks.

AndiGeeky
  • 11,266
  • 6
  • 50
  • 66
  • Thank You for the reply. – AGM Sep 11 '15 at 08:02
  • @user777 : Always welcome.Please accept answer if it helps you. – AndiGeeky Sep 11 '15 at 08:04
  • Can you please provide me the code for Activity class if any because i am facing issues while intializing the helper class. – AGM Sep 14 '15 at 05:03
  • @Ananth mahale : Please add " locationUtility = new LocationUtility(HomeActivity.this, null); " in onCreate() of an activity.!! – AndiGeeky Sep 14 '15 at 05:07
  • @ Ananth mahale : My Pleasure..! – AndiGeeky Sep 14 '15 at 05:11
  • I have intialized the Helper class in onCreate() method and accessed the methods of helper class in Activity class But its throwing NullPointer Exception. By the logs what i understood is the onLocationChanged() method is not acessed. Can you please help in this? – AGM Sep 14 '15 at 10:03
  • @ Ananth mahale : Do your location service is enable ? – AndiGeeky Sep 14 '15 at 10:18
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/89573/discussion-between-ananth-mahale-and-mamata-gelanee). – AGM Sep 14 '15 at 10:40