Приложение вылетает при запуске службы

Я использую GoogleFusedLocationAPI, и у меня есть 2 service в моем приложении. Моя услуга предназначена для приведенной ниже причины, а имя такое же, как

A- BackGroundService (будет отслеживать местоположение каждые 2 минуты)

B- TripStartedService (будет отслеживать местоположение каждые 10 секунд)

  1. Для обнаружения поездки каждые 2 минуты, если пользователь находится на расстоянии 50 м. (BackGroundService)
  2. Если пользователь покрывает 50 метров, определение местоположения происходит каждые 10 секунд.(TripStartedService)

Я могу запустить службу и местоположение, все в порядке. Но когда я закрываю TripStartedService и запускаю BackGroundService, чтобы снова обнаружить новую поездку, я получаю это исключение.

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)

 

Я знаю, что по SOF куча вопросов, но все же я беспомощен. Поэтому, пожалуйста, дайте мне знать, где я делаю ошибку. Мой класс обслуживания ниже. Я получаю исключения в stopLocationUpdates(); от onDestroy(). Любая помощь будет ценной..

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

person Community    schedule 09.01.2018    source источник
comment
Возможный дубликат Вызвано: java.lang.IllegalStateException: GoogleApiClient еще не подключен   -  person ADM    schedule 09.01.2018
comment
Вы должны начать locationUpdates по методу onConnected().   -  person Aditya    schedule 09.01.2018
comment
@ Heisen-Berg Спасибо за быстрый ответ, но не могли бы вы объяснить мне немного больше. Я застрял с этой проблемой более 4 дней. :(   -  person    schedule 09.01.2018
comment
@Heisen-Berg Как запустить LocationUpdates в методе onConnected()?   -  person    schedule 09.01.2018
comment
Пожалуйста, добавьте свой полный logcat.   -  person Aditya    schedule 09.01.2018
comment
@ Heisen-Berg Сэр.. Позвольте мне пару минут...   -  person    schedule 09.01.2018
comment
@ Heisen-Berg Да, сэр, я обновил свой логарифм. Пожалуйста, просмотрите мой вопрос...   -  person    schedule 09.01.2018
comment
Согласно вашему журналу, вы получаете исключение onDestroy. Проверьте, подключен ли GoogleApiClient до stopLocationUpdates. Если клиент API подключен, сделайте это.   -  person Aditya    schedule 09.01.2018
comment
@ Heisen-Berg, да, вы правы, сэр ... Как я могу решить эту проблему. Я не могу понять. Пожалуйста, дайте мне фрагмент.   -  person    schedule 09.01.2018