应用程序的哪个部分应该在服务中?

时间:2014-05-01 13:07:11

标签: android

我正在使用定期位置更新,并想知道哪个部分应该投入使用,以便即使应用程序关闭它也会继续运行。这是代码

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 个答案:

答案 0 :(得分:1)

@Override
public void onLocationChanged(Location location) {

} 

是位置更改时调用的回调。因此,这应该放在您的服务中,以便它能够接收更新。