应用程序在启动服务时崩溃

时间:2018-01-09 10:23:17

标签: android android-fusedlocation

我正在使用GoogleFusedLocationAPI,我的应用中有2 service。我的服务是出于以下原因,名称为

A- BackGroundService(这将每2分钟跟踪一次位置)

B- TripStartedService(这将每隔10秒跟踪一次位置)

  1. 如果用户距离为50 mtr,则每2分钟检测一次Trip。的(BackGroundService)
  2. 如果用户覆盖50 mtr,则每隔10秒检测一次位置。(TripStartedService)
  3. 我可以启动服务和位置获得veri罚款。但是当我关闭 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();
            }
    

0 个答案:

没有答案