在活动中调用服务

时间:2015-06-23 17:33:38

标签: android service google-api-client location-services

在Activity中调用此特定服务的最简单方法是什么?我想让它在后台运行,同时我将连续的位置更新发送到我的MainActivity。任何建议都将不胜感激。

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

// LogCat tag
private static final String TAG = LocationService.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 void onCreate() {
    super.onCreate();

    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API).build();

}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (mGoogleApiClient != null) {
        mGoogleApiClient.connect();
        togglePeriodicLocationUpdates();
    }
    return START_NOT_STICKY;
}

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

protected void createLocationRequest() {
    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(UPDATE_INTERVAL);
    mLocationRequest.setFastestInterval(FATEST_INTERVAL);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
}

private void togglePeriodicLocationUpdates() {
    mGoogleApiClient.connect();

    if (!mRequestingLocationUpdates) {

        mRequestingLocationUpdates = true;

        startLocationUpdates();

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

    } else {

        mRequestingLocationUpdates = false;

        // Stopping the location updates
        stopLocationUpdates();

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

protected void stopLocationUpdates() {
    LocationServices.FusedLocationApi.removeLocationUpdates(
            mGoogleApiClient, this);
}

protected void startLocationUpdates() {
    mGoogleApiClient.connect();
    LocationServices.FusedLocationApi.requestLocationUpdates(
            mGoogleApiClient, mLocationRequest, this);

}

@Override
public void onConnected(Bundle arg0) {
    createLocationRequest();
}

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

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

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

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

@Override
public boolean stopService(Intent name) {
    return super.stopService(name);
}

2 个答案:

答案 0 :(得分:0)

应用程序可以在Context.startService方法的帮助下启动服务。如果尚未创建服务,该方法将调用服务的onCreate方法;否则将调用onStart方法。这是代码:

Intent serviceIntent = new Intent();
serviceIntent.setAction("com.testApp.service.MY_SERVICE");
startService(serviceIntent);

答案 1 :(得分:0)

您可以使用If you're not going。使用它在BroadcastReceiver中注册Activity,并在您更新位置时从您的服务广播新坐标。要注册/取消注册接收器,您可以使用

LocalBroadcastManager.getInstance(this).registerReceiver

LocalBroadcastManager.getInstance(this).unregisterReceiver

要广播您必须使用的意图

LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

您的广播接收器将获得您广播的意图