2014-05-01 69 views
0

我正在使用定期的位置更新,並想知道哪個部分應該投入使用,以便即使應用程序關閉,它也會繼續運行。下面是代碼應用程序的哪些部分應該在服務中?

public class MainActivity extends FragmentActivity implements LocationListener, 
    GooglePlayServicesClient.ConnectionCallbacks, 
    GooglePlayServicesClient.OnConnectionFailedListener { 

private LocationRequest mLocationRequest; 
private LocationClient mLocationClient; 
private TextView mLatLng; 
private TextView mConnectionState; 
private TextView mConnectionStatus; 
SharedPreferences mPrefs; 
SharedPreferences.Editor mEditor; 
boolean mUpdatesRequested = false; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    mLatLng = (TextView) findViewById(R.id.lat_lng); 
    mConnectionState = (TextView) findViewById(R.id.text_connection_state); 
    mConnectionStatus = (TextView) findViewById(R.id.text_connection_status); 

    mLocationRequest = LocationRequest.create(); 
    mLocationRequest 
      .setInterval(LocationUtils.UPDATE_INTERVAL_IN_MILLISECONDS); 
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 
    mLocationRequest 
      .setFastestInterval(LocationUtils.FAST_INTERVAL_CEILING_IN_MILLISECONDS); 
    mUpdatesRequested = false; 
    mPrefs = getSharedPreferences(LocationUtils.SHARED_PREFERENCES, 
      Context.MODE_PRIVATE); 
    mEditor = mPrefs.edit(); 
    mLocationClient = new LocationClient(this, this, this); 

} 

@Override 
public void onStop() { 
    if (mLocationClient.isConnected()) { 
     stopPeriodicUpdates(); 
    } 
    mLocationClient.disconnect(); 
    super.onStop(); 
} 

@Override 
public void onPause() { 
    mEditor.putBoolean(LocationUtils.KEY_UPDATES_REQUESTED, 
      mUpdatesRequested); 
    mEditor.commit(); 
    super.onPause(); 
} 

@Override 
public void onStart() { 
    super.onStart(); 
    mLocationClient.connect(); 

} 

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

    // If the app already has a setting for getting location updates, get it 
    if (mPrefs.contains(LocationUtils.KEY_UPDATES_REQUESTED)) { 
     mUpdatesRequested = mPrefs.getBoolean(
       LocationUtils.KEY_UPDATES_REQUESTED, false); 

     // Otherwise, turn off location updates until requested 
    } else { 
     mEditor.putBoolean(LocationUtils.KEY_UPDATES_REQUESTED, false); 
     mEditor.commit(); 
    } 

} 

@Override 
protected void onActivityResult(int requestCode, int resultCode, 
     Intent intent) { 

    // Choose what to do based on the request code 
    switch (requestCode) { 

    // If the request code matches the code sent in onConnectionFailed 
    case LocationUtils.CONNECTION_FAILURE_RESOLUTION_REQUEST: 

     switch (resultCode) { 
     // If Google Play services resolved the problem 
     case Activity.RESULT_OK: 

      // Log the result 
      Log.d(LocationUtils.APPTAG, getString(R.string.resolved)); 

      // Display the result 
      mConnectionState.setText(R.string.connected); 
      mConnectionStatus.setText(R.string.resolved); 
      break; 

     // If any other result was returned by Google Play services 
     default: 
      // Log the result 
      Log.d(LocationUtils.APPTAG, getString(R.string.no_resolution)); 

      // Display the result 
      mConnectionState.setText(R.string.disconnected); 
      mConnectionStatus.setText(R.string.no_resolution); 

      break; 
     } 

     // If any other request code was received 
    default: 
     // Report that this Activity received an unknown requestCode 
     Log.d(LocationUtils.APPTAG, 
       getString(R.string.unknown_activity_request_code, 
         requestCode)); 

     break; 
    } 
} 

private boolean servicesConnected() { 

    // Check that Google Play services is available 
    int resultCode = GooglePlayServicesUtil 
      .isGooglePlayServicesAvailable(this); 

    // If Google Play services is available 
    if (ConnectionResult.SUCCESS == resultCode) { 
     // In debug mode, log the status 
     Log.d(LocationUtils.APPTAG, 
       getString(R.string.play_services_available)); 

     // Continue 
     return true; 
     // Google Play services was not available for some reason 
    } else { 
     // Display an error dialog 
     Dialog dialog = GooglePlayServicesUtil.getErrorDialog(resultCode, 
       this, 0); 
     if (dialog != null) { 
      ErrorDialogFragment errorFragment = new ErrorDialogFragment(); 
      errorFragment.setDialog(dialog); 
      errorFragment.show(getFragmentManager(), LocationUtils.APPTAG); 
     } 
     return false; 
    } 
} 

public void getLocation(View v) { 
    if (servicesConnected()) { 
     Location currentLocation = mLocationClient.getLastLocation(); 
     mLatLng.setText(LocationUtils.getLatLng(this, currentLocation)); 
    } 
} 

public void startUpdates(View v) { 
    mUpdatesRequested = true; 
    if (servicesConnected()) { 
     startPeriodicUpdates(); 
    } 
} 

public void stopUpdates(View v) { 
    mUpdatesRequested = false; 
    if (servicesConnected()) { 
     stopPeriodicUpdates(); 
    } 
} 

@Override 
public void onConnected(Bundle bundle) { 
    mConnectionStatus.setText(R.string.connected); 
    if (mUpdatesRequested) { 
     startPeriodicUpdates(); 
    } 
} 

@Override 
public void onDisconnected() { 
    mConnectionStatus.setText(R.string.disconnected); 
} 

@Override 
public void onConnectionFailed(ConnectionResult connectionResult) { 

    /* 
    * Google Play services can resolve some errors it detects. If the error 
    * has a resolution, try sending an Intent to start a Google Play 
    * services activity that can resolve error. 
    */ 
    if (connectionResult.hasResolution()) { 
     try { 

      // Start an Activity that tries to resolve the error 
      connectionResult.startResolutionForResult(this, 
        LocationUtils.CONNECTION_FAILURE_RESOLUTION_REQUEST); 

      /* 
      * Thrown if Google Play services canceled the original 
      * PendingIntent 
      */ 

     } catch (IntentSender.SendIntentException e) { 

      // Log the error 
      e.printStackTrace(); 
     } 
    } else { 

     // If no resolution is available, display a dialog to the user with 
     // the error. 
     showErrorDialog(connectionResult.getErrorCode()); 
    } 
} 

@Override 
public void onLocationChanged(Location location) { 
    mConnectionStatus.setText(R.string.location_updated); 
    mLatLng.setText(LocationUtils.getLatLng(this, location)); 
} 

private void startPeriodicUpdates() { 
    mLocationClient.requestLocationUpdates(mLocationRequest, this); 
    mConnectionState.setText(R.string.location_requested); 
} 

private void stopPeriodicUpdates() { 
    mLocationClient.removeLocationUpdates(this); 
    mConnectionState.setText(R.string.location_updates_stopped); 
} 

private void showErrorDialog(int errorCode) { 
    Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog(errorCode, 
      this, LocationUtils.CONNECTION_FAILURE_RESOLUTION_REQUEST); 
    if (errorDialog != null) { 
     ErrorDialogFragment errorFragment = new ErrorDialogFragment(); 
     errorFragment.setDialog(errorDialog); 
     errorFragment.show(getFragmentManager(), LocationUtils.APPTAG); 
    } 
} 

public static class ErrorDialogFragment extends DialogFragment { 
    private Dialog mDialog; 

    public ErrorDialogFragment() { 
     super(); 
     mDialog = null; 
    } 

    public void setDialog(Dialog dialog) { 
     mDialog = dialog; 
    } 

    @Override 
    public Dialog onCreateDialog(Bundle savedInstanceState) { 
     return mDialog; 
    } 
} 
} 

回答

1
@Override 
public void onLocationChanged(Location location) { 

} 

被這就是所謂的位置發生變化時的回調。所以,這應該放在您的服務中,以便它能夠接收更新。

+0

謝謝。 startPeriodicUpdates怎麼樣?我希望在應用程序打開時定期更新應該開始運行,除非用戶決定停止它們。 –

+0

是的,您的服務必須註冊才能收到更新。另外,當服務被破壞時,您必須停止接收更新。這兩個片段都會在服務的定義中出現。 – Swayam

+0

請幫我用代碼。我嘗試了很多選項,但仍然無法完成它 –

相關問題