0

I am Using GoogleFusedLocationAPI and I have 2 service in my App. My service is meant for below reason and Name is as

A- BackGroundService (This will Track Location in every 2 minutes)

B- TripStartedService(This will Track Location In every 10 seconds)

  1. To detect Trip in every 2 minutes if user distance is 50 mtr. (BackGroundService)
  2. If user cover 50 mtr then detect location is every 10 seconds.(TripStartedService)

I am able to start Service and Location getting veri fine. But When I am closing TripStartedService and Starting BackGroundService to detect again new trip then I am getting this exception.

FATAL EXCEPTION: main
    Process: com.com.xxxxx.xxxxxxx, PID: 31551
    java.lang.RuntimeException: Unable to stop service com.com.xxxxx.xxxxxxx.services.BackgroundLocationService@74441c6: java.lang.IllegalStateException: GoogleApiClient is not connected yet.
    at android.app.ActivityThread.handleStopService(ActivityThread.java:3060)
    at android.app.ActivityThread.-wrap21(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5438)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:762)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:652)
    Caused by: java.lang.IllegalStateException: GoogleApiClient is not connected yet.
    at com.google.android.gms.internal.zzaaj.zzb(Unknown Source)
    at com.google.android.gms.internal.zzaan.zzb(Unknown Source)
    at com.google.android.gms.internal.zzaal.zzb(Unknown Source)
    at com.google.android.gms.internal.zzarl.removeLocationUpdates(Unknown Source)
    at com.xxxxx.xxxxxxx.services.BackgroundLocationService.stopLocationUpdates(BackgroundLocationService.java:103)
    at com.xxxxx.xxxxxxx.services.BackgroundLocationService.onDestroy(BackgroundLocationService.java:134)
    at android.app.ActivityThread.handleStopService(ActivityThread.java:3041)
    at android.app.ActivityThread.-wrap21(ActivityThread.java) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448) 
    at android.os.Handler.dispatchMessage(Handler.java:102) 
    at android.os.Looper.loop(Looper.java:148) 
    at android.app.ActivityThread.main(ActivityThread.java:5438) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:762) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:652)

 

I know there is tons of questions on SOF but still I am helpless So please let me know where I am doing mistake. My service class is Below. I am getting exceptions in stopLocationUpdates(); from onDestroy(). Any Help would be Appreciable..

BackGroundService.class

public class BackgroundLocationService extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {

protected static final String TAG = "BackService";

public static long UPDATE_INTERVAL_IN_MILLISECONDS = 1000*2;
public static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = UPDATE_INTERVAL_IN_MILLISECONDS / 2;
public GoogleApiClient mGoogleApiClient;
public LocationRequest mLocationRequest;
private PendingIntent mPendingIntent;
IBinder mBinder = new LocalBinder();

private class LocalBinder extends Binder {
    public BackgroundLocationService getServerInstance() {
        return BackgroundLocationService.this;
    }
}

@Override
public void onCreate() {
    super.onCreate();
    Log.i(TAG, "onCreate()");

    Intent mIntentService = new Intent(this, LocationUpdates.class);
    mPendingIntent = PendingIntent.getService(this, 1, mIntentService, PendingIntent.FLAG_UPDATE_CURRENT);

    buildGoogleApiClient();
}

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

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    super.onStartCommand(intent, flags, startId);

    if (mGoogleApiClient.isConnected()) {
        Log.i(TAG + " onStartCmd", "Connected");
        return START_STICKY;
    }

    if (!mGoogleApiClient.isConnected() || !mGoogleApiClient.isConnecting()) {
        Log.i(TAG + " onStartCmd", "GoogleApiClient not Connected");
        mGoogleApiClient.connect();
    }

    return START_STICKY;
}

protected synchronized void buildGoogleApiClient() {
    Log.i(TAG, "Building GoogleApiClient");
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
    mGoogleApiClient.connect();
    createLocationRequest();
}

protected void createLocationRequest() {
    Log.i(TAG, "createLocationRequest()");
    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
    mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}

protected void startLocationUpdates() {
    Log.i(TAG, "Started Location Updates");
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;
    }
    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, mPendingIntent);
}

public void stopLocationUpdates() {
    Log.i(TAG, "Stopped Location Updates");
    LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, mPendingIntent);
}

@Override
public void onConnected(Bundle connectionHint) {
    Log.i(TAG, "Connected to GoogleApiClient");
    startLocationUpdates();
}

@Override
public void onLocationChanged(Location location) {

    String message = "Latitude : " + location.getLatitude() + "\n Longitude : " + location.getLongitude() +
            "\n location Accuracy: " + location.getAccuracy() + "\n speed: " + location.getSpeed();
    Log.d(TAG, "onLocationChanged: " + message);
}

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

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

@Override
public void onDestroy() {
    super.onDestroy();
    stopLocationUpdates();

}

}

This is where I am stopping my service and starting again service

Method to Stop and Start Service

 //This Code clock will return true if Trip completed Successfully.
            if (trip_counts > (TRIP_COMPLETION_CHECK_INTERVAL * NUMBER_OF_LOCATION_FETCH_IN_MINUTE)
                    && trip_counts % NUMBER_OF_LOCATION_FETCH_IN_MINUTE == 0) {


                float total_distance = database.getTotalDistance();
                Log.e("Distance", "calculateTrip: " + total_distance);
                if (total_distance < ACTIVE_TRIP_MIN_DISTANCE) {
                    Log.d("TRIP STATUS", "calculateTrip: Trip Stopped !!!");
                    Date date_local = new Date();
                    SimpleDateFormat sdf_format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                    sdf_format.setTimeZone(TimeZone.getTimeZone("UTC"));
                    Date gmt = new Date(sdf_format.format(date_local));

                    String utc_time = sdf_format.format(gmt);

                    database.updateTripHistory("", MethodUtils.epochTimeConvert(utc_time), TripStatus.TRIP_COMPLETED);


                    NotificationManager notificationManager = (NotificationManager) activity.getSystemService(NOTIFICATION_SERVICE);
                    NotificationCompat.Builder notification = new NotificationCompat.Builder(activity);

                    notification.setContentTitle("TITLE");
                    notification.setContentText("\n Trip Completed...");
                    notification.setSmallIcon(R.drawable.big_marker);
                    notificationManager.notify(4321, notification.build());


                    activity.stopService(new Intent(activity, TripStartedService.class));
                    Log.i("Stoped Trip Srvce ", "calculateTrip: ");
                    Log.i("Stoped Trip Srvce ", "================== Started BackGroundService Again: ============ ");
                    activity.startService(new Intent(activity, BackgroundLocationService.class));
                    Log.i("Started BG Track Srvce", "calculateTrip: ");

                    //Delete extra rows
                    //SELECT _id FROM trip_started order by _id desc limit 1 offset 5-1;

                }
            }

            Log.e("Trip Database Rows Size", "" + trip_counts + "\t \tBackGroundTable Rows : " + back_counts + "\tGPS>>>: " + Boolean.toString(isGpsEnabled));
            activity.stopService(new Intent(activity, BackgroundLocationService.class));
        } catch (Exception e) {
            e.printStackTrace();
        }
Sneh Pandya
  • 8,197
  • 7
  • 35
  • 50
  • 2
    Possible duplicate of [Caused by: java.lang.IllegalStateException: GoogleApiClient is not connected yet](https://stackoverflow.com/questions/35853657/caused-by-java-lang-illegalstateexception-googleapiclient-is-not-connected-yet) – ADM Jan 09 '18 at 10:29
  • You have to start `locationUpdates` on `onConnected()` method. – Aditya Jan 09 '18 at 10:30
  • @Heisen-Berg Thnxx for quick reply but Can You explain me little bit more. I stucked with this issue more than 4 days. :( –  Jan 09 '18 at 10:31
  • @Heisen-Berg How can I start LocationUpdates in onConnected() method ? –  Jan 09 '18 at 10:32
  • Please add your full logcat. – Aditya Jan 09 '18 at 10:33
  • @Heisen-Berg Sir.. Allow me couple of minutes... –  Jan 09 '18 at 10:36
  • @Heisen-Berg Yes Sir I updated my logcat .Please review my question... –  Jan 09 '18 at 10:39
  • According to your log, you are getting exception on `onDestroy`. Check `GoogleApiClient` is connected or not before `stopLocationUpdates`. If api client is connected then do it. – Aditya Jan 09 '18 at 10:42
  • @Heisen-Berg yes You are right sir... How can I overcome to this problem. I am unable to understand. Please give me some snippet. –  Jan 09 '18 at 10:44

0 Answers0