暂停活动时启动服务

时间:2014-08-29 10:55:44

标签: android background location android-service

我正在创建一个将用户的位置显示在地图中的应用,现在我想在应用处于后台时更新用户位置,尤其是我想在Service时启动调用Activity方法onPause()

我的活动:

public class MapsActivity extends Activity implements OnClickListener, GooglePlayServicesClient.ConnectionCallbacks,
        GooglePlayServicesClient.OnConnectionFailedListener, LocationListener, OnInfoWindowClickListener {

    private static final long UPDATE_INTERVAL = 5000;
    private static final long FASTEST_INTERVAL = 1000;
    private GoogleMap map = null;
    private LocationClient locationClient;
    private Location myLocation;
    private LocationRequest locationRequest;
    private LatLng newPosition;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map);
        map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
        map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        locationClient = new LocationClient(this, this, this);
        locationRequest = LocationRequest.create().setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY).setInterval(UPDATE_INTERVAL)
                .setFastestInterval(FASTEST_INTERVAL).setSmallestDisplacement(10);
        if (locationClient != null)
            // connect the client to the Google Play services
            locationClient.connect();
    }

    @Override
    public void onLocationChanged(Location location) {
        newPosition = new LatLng(location.getLatitude(), location.getLongitude());
        myLocation = location;
        if (myLocation != null)
            button.setClickable(true);
        else
            button.setClickable(false);
        map.animateCamera(CameraUpdateFactory.newLatLngZoom(newPosition, 20));
    }

    @Override
    public void onConnectionFailed(ConnectionResult arg0) {
    }

    @Override
    public void onConnected(Bundle arg0) {
        Toast.makeText(this, "I'm bringing you to your area.", Toast.LENGTH_SHORT).show();
        // start periodic updates
        locationClient.requestLocationUpdates(locationRequest, this);
    }

    @Override
    public void onDisconnected() {
        Toast.makeText(this, "Disconnected. Please re-connect.", Toast.LENGTH_SHORT).show();
    }

    public ProgressDialog getProgress() {
        return progress;
    }

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

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

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

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        if (locationClient.isConnected() && locationClient != null) {
            locationClient.removeLocationUpdates(this);
            locationClient.disconnect();
        }
        super.onDestroy();
    }

}

我的服务类:

public class locationBackgroundService extends Service implements LocationListener, GooglePlayServicesClient.ConnectionCallbacks,
        GooglePlayServicesClient.OnConnectionFailedListener {

    private LocationRequest mLocationRequest;
    private LocationClient mLocationClient;

    public locationBackgroundService() {

    }

    @Override
    public void onCreate() {
        mLocationRequest = LocationRequest.create();
        // mLocationRequest.setInterval(CommonUtils.UPDATE_INTERVAL_IN_MILLISECONDS);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        // mLocationRequest.setFastestInterval(CommonUtils.FAST_INTERVAL_CEILING_IN_MILLISECONDS);
        mLocationClient = new LocationClient(getApplicationContext(), this, this);
        mLocationClient.connect();
    }


    @Override
    public void onStart(Intent intent, int startId) {
        int start = Service.START_STICKY;
    }

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


    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
    }

    @Override
    public void onConnected(Bundle arg0) {
        Log.i("info", "Location Client is Connected");
        mLocationClient.requestLocationUpdates(mLocationRequest, this);
        Log.i("info", "Service Connect status :: " + isServicesConnected());
    }

    @Override
    public void onDisconnected() {
        Log.i("info", "Location Client is Disconnected");
    }

    @Override
    public void onLocationChanged(Location location) {
        double latitude = location.getLatitude();
        double longitude = location.getLongitude();
    }


    private boolean isServicesConnected() {
        // Check that Google Play services is available
        int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(locationBackgroundService.this);

        // If Google Play services is available
        if (ConnectionResult.SUCCESS == resultCode) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void onDestroy() {
        mLocationClient.removeLocationUpdates(this);
        super.onDestroy();
    }

}

可以这样做吗?

提前感谢。

1 个答案:

答案 0 :(得分:0)

LocationService.class的例子

package com.example.myapp;

import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.example.myapp.activities.MainActivity;

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

    public static final String LOCATION_SERVICE = "LocationService";
    private LocationClient mLocationClient;
    private LocationRequest mLocationRequest;
    float minDist = 100f;
    int minTime = 10000;
    PendingIntent contentIntent;
    public static String USER_LATITUDE = "user_latitude";
    public static String USER_LONGITUDE = "user_longitude";

    @Override
    public void onCreate() {
        Log.d("onCreate", "");
        super.onCreate();
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        contentIntent = PendingIntent.getActivity(this, 0, intent, 0);
        mLocationClient = new LocationClient(this, this, this);
        mLocationRequest = LocationRequest.create();
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setInterval(minTime);
        //mLocationRequest.setSmallestDisplacement(minDist);
    }

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

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        mLocationClient.connect();
        return Service.START_NOT_STICKY;
    }

    @Override
    public void onLocationChanged(Location location) {
        float latitude = (float) location.getLatitude();
        float longitude = (float) location.getLongitude();
        Log.d("onLocationChanged. latLng", latitude + ", " + longitude);
        Intent intent = new Intent(LOCATION_SERVICE);
        intent.putExtra(USER_LATITUDE, latitude);
        intent.putExtra(USER_LONGITUDE, longitude);
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    }

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

    @Override
    public void onConnected(Bundle bundle) {
        Log.d(LOCATION_SERVICE, "onConnected");
        startPeriodicUpdates();
    }

    @Override
    public void onDisconnected() {
        Log.d(LOCATION_SERVICE, "onDisconnected");
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        Log.d(LOCATION_SERVICE, "onConnectionFailed");
    }

    public void startPeriodicUpdates() {
        mLocationClient.requestLocationUpdates(mLocationRequest, this);
        Log.d(LOCATION_SERVICE, "startPeriodicUpdates");
    }

    private void stopPeriodicUpdates() {
        mLocationClient.removeLocationUpdates(this);
        Log.d(LOCATION_SERVICE, "stopPeriodicUpdates");
    }
}

添加MainActivity.class

private boolean servicesConnected() {
    int resultCode =
            GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
    if (ConnectionResult.SUCCESS == resultCode) {
        Log.d("servicesConnected", "Google play services isConnected");
        return true;
    } else {
        return false;
    }
}

private BroadcastReceiver mLocationReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        float latitude = intent.getFloatExtra(LocationService.USER_LATITUDE, 0);
        float longitude = intent.getFloatExtra(LocationService.USER_LONGITUDE, 0);
        //do something
    }
};

@Override
public void onPause() {
    super.onPause();
    Intent service = new Intent(this, LocationService.class);

    IntentFilter intentLocationServiceFilter = new IntentFilter(LocationService
            .LOCATION_SERVICE);
    LocalBroadcastManager.getInstance(this)
            .registerReceiver(mLocationReceiver, intentLocationServiceFilter);
    if (servicesConnected()) {
        startService(service);
    }
}

不要忘记将AndroidManifest文件添加到LocationService