2015-05-27 2 views
-1

Я работаю над service в android, но я столкнулся ошибку, котораяIllegalStateException Ошибка в классе обслуживания

Caused by: java.lang.IllegalStateException: GoogleApiClient is not connected yet. 
      at com.google.android.gms.common.api.zzf.zzb(Unknown Source) 
      at com.google.android.gms.common.api.zzg.zzb(Unknown Source) 
      at com.google.android.gms.location.internal.zzd.requestLocationUpdates(Unknown Source) 
      at com.example.mine4.newapp.MyService.startLocationUpdates(MyService.java:180) 
      at com.example.mine4.newapp.MyService.togglePeriodicLocationUpdates(MyService.java:123) 
      at com.example.mine4.newapp.MyService.onCreate(MyService.java:62) 
      at android.app.ActivityThread.handleCreateService(ActivityThread.java:2716) 
            at android.app.ActivityThread.access$1600(ActivityThread.java:165) 
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1455) 
            at android.os.Handler.dispatchMessage(Handler.java:107) 
            at android.os.Looper.loop(Looper.java:194) 
            at android.app.ActivityThread.main(ActivityThread.java:5391) 
            at java.lang.reflect.Method.invokeNative(Native Method) 
            at java.lang.reflect.Method.invoke(Method.java:525) 
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833) 
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600) 
            at dalvik.system.NativeStart.main(Native Method) 

и мой код здесь:

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

    private static final String TAG = MyService.class.getSimpleName(); 

    private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000; 

    private Location mLastLocation; 

    // Google client to interact with Google API 
    private GoogleApiClient mGoogleApiClient; 

    // boolean flag to toggle periodic location updates 
    private boolean mRequestingLocationUpdates = false; 

    private LocationRequest mLocationRequest; 

    // Location updates intervals in sec 
    private static int UPDATE_INTERVAL = 10000; // 10 sec 
    private static int FATEST_INTERVAL = 5000; // 5 sec 
    private static int DISPLACEMENT = 10; // 10 meters 


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

    @Override 
    public void onCreate() { 
     super.onCreate(); 
     if (checkPlayServices()) { 

      // Building the GoogleApi client 
      buildGoogleApiClient(); 

      createLocationRequest(); 
     } 
     displayLocation(); 
     togglePeriodicLocationUpdates(); 
    } 
    @Override 
    public void onStart(Intent intent, int startId) { 
     super.onStart(intent, startId); 
     if (mGoogleApiClient != null) { 
      mGoogleApiClient.connect(); 
     } 
    } 

// @Override 
// protected void onResume() { 
//  super.onResume(); 
// 
//  checkPlayServices(); 
// 
//  // Resuming the periodic location updates 
//  if (mGoogleApiClient.isConnected() && mRequestingLocationUpdates) { 
//   startLocationUpdates(); 
//  } 
// } 
// 
// @Override 
// protected void onStop() { 
//  super.onStop(); 
//  if (mGoogleApiClient.isConnected()) { 
//   mGoogleApiClient.disconnect(); 
//  } 
// } 
// @Override 
// protected void onPause() { 
//  super.onPause(); 
//  stopLocationUpdates(); 
// } 

    /** 
    * Method to display `location` on UI 
    * */ 
    private void displayLocation() { 

     mLastLocation = LocationServices.FusedLocationApi 
       .getLastLocation(mGoogleApiClient); 

     if (mLastLocation != null) { 
      double latitude = mLastLocation.getLatitude(); 
      double longitude = mLastLocation.getLongitude(); 



     } else { 
     } 
    } 
    private void togglePeriodicLocationUpdates() { 
     if (!mRequestingLocationUpdates) { 
      // Changing the button text 



      mRequestingLocationUpdates = true; 

      // Starting the location updates 
      startLocationUpdates(); 

      Log.d(TAG, "Periodic location updates started!"); 

     } else { 
      // Changing the button text 



      mRequestingLocationUpdates = false; 

      // Stopping the location updates 
      stopLocationUpdates(); 

      Log.d(TAG, "Periodic location updates stopped!"); 
     } 
    } 
    protected synchronized void buildGoogleApiClient() { 
     mGoogleApiClient = new GoogleApiClient.Builder(this) 
       .addConnectionCallbacks(this) 
       .addOnConnectionFailedListener(this) 
       .addApi(LocationServices.API).build(); 
    } 

    /** 
    * Creating location request object 
    * */ 
    protected void createLocationRequest() { 
     mLocationRequest = new LocationRequest(); 
     mLocationRequest.setInterval(UPDATE_INTERVAL); 
     mLocationRequest.setFastestInterval(FATEST_INTERVAL); 
     mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 
     mLocationRequest.setSmallestDisplacement(DISPLACEMENT); 
    } 


    private boolean checkPlayServices() { 
     int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this); 
     if (resultCode != ConnectionResult.SUCCESS) { 
      if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) { 
       GooglePlayServicesUtil.getErrorString(resultCode); 
      } else { 
       Toast.makeText(getApplicationContext(), 
         "This device is not supported.", Toast.LENGTH_LONG) 
         .show(); 

      } 
      return false; 
     } 
     return true; 
    } 

    /** 
    * Starting the location updates 
    * */ 
    protected void startLocationUpdates() { 

     LocationServices.FusedLocationApi.requestLocationUpdates(
       mGoogleApiClient, mLocationRequest, this); 

    } 

    /** 
    * Stopping location updates 
    */ 
    protected void stopLocationUpdates() { 
     LocationServices.FusedLocationApi.removeLocationUpdates(
       mGoogleApiClient, this); 
    } 

    /** 
    * Google api callback methods 
    */ 
    @Override 
    public void onConnectionFailed(ConnectionResult result) { 
     Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " 
       + result.getErrorCode()); 
    } 

    @Override 
    public void onConnected(Bundle arg0) { 

     // Once connected with google api, get the location 
     displayLocation(); 

     if (mRequestingLocationUpdates) { 
      startLocationUpdates(); 
     } 
    } 

    @Override 
    public void onConnectionSuspended(int arg0) { 
     mGoogleApiClient.connect(); 
    } 

    @Override 
    public void onLocationChanged(Location location) { 
     // Assign the new location 
     mLastLocation = location; 

     Toast.makeText(getApplicationContext(), "Location changed!", 
       Toast.LENGTH_SHORT).show(); 

     // Displaying the new location on UI 
     displayLocation(); 
    } 

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

    } 
    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 

     return super.onStartCommand(intent, flags, startId); 
    } 
} 

и ошибка здесь:

protected void startLocationUpdates() { 

    LocationServices.FusedLocationApi.requestLocationUpdates(
      mGoogleApiClient, mLocationRequest, this); 

} 

Я впервые пользуюсь службой, и мне нужно работать на службу e мой локатор gps, который работает на фоне.

ответ

0

Просто, необходимо раскомментировать следующую часть, которая отвечает за подключение к API Google, когда service или activity начинается и остановить onStop()

@Override 
protected void onResume() { 
    super.onResume(); 

    checkPlayServices(); 

    // Resuming the periodic location updates 
    if (mGoogleApiClient.isConnected() && mRequestingLocationUpdates) { 
     startLocationUpdates(); 
    } 
} 

@Override 
protected void onStop() { 
    super.onStop(); 
    if (mGoogleApiClient.isConnected()) { 
     mGoogleApiClient.disconnect(); 
    } 
} 

@Override 
protected void onPause() { 
    super.onPause(); 
    stopLocationUpdates(); 
} 
+0

, но эти методы дают ошибку в службе –

+0

По крайней мере, ' onResume' и 'onStop' являются обязательными. Вы должны расколоть их и разобраться с ошибкой. @ChaudryJunaidSaifUllahChadh –

Смежные вопросы