Android Location service didn't work in backgr

2019-02-25 05:29发布

问题:

I am working on a Location-App which should begin to track some statistic data based on longitude and latitude when the user presses a Button. All this stuff works very well but when it comes to lock the screen or put the app in the background the service does not work anymore !

I have read a lot about background services and Broadcast receivers but I don't know how to implement the Google API Location listener in a Service and where to implement this class in the MainActivity. Can anyone tell me with a short code example how to implement such a service or a link where this is explained ?

回答1:

Use fuse location service and save updated location every time

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

    LocationRequest mLocationRequest;
    GoogleApiClient mGoogleApiClient;
    public static Location mCurrentLocation;

    .............................

    @Override
    public void onCreate() {

        //show error dialog if GoolglePlayServices not available
        if (isGooglePlayServicesAvailable()) {
            mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(BACKGROUND_INTERVAL);  
        mLocationRequest.setFastestInterval(BACKGROUND_INTERVAL);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        //mLocationRequest.setSmallestDisplacement(10.0f);  /* min dist for location change, here it is 10 meter */
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addApi(LocationServices.API)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .build();

            mGoogleApiClient.connect();
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
         return super.onStartCommand(intent, flags, startId);
    }

    //Check Google play is available or not
    private boolean isGooglePlayServicesAvailable() {
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
        return ConnectionResult.SUCCESS == status;
    }


    @Override
    public void onConnected(Bundle bundle) {
        startLocationUpdates();
    }

    protected void startLocationUpdates() {
        try {
             PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(
                    mGoogleApiClient, mLocationRequest, this);
        } catch (IllegalStateException e) {}
    }

    @Override
    public void onLocationChanged(Location location) {

        //Save your location
    }
    ............................
}

you can get current location onLocationChanged()

For more details check http://javapapers.com/android/android-location-fused-provider/ or follow official guide https://developer.android.com/training/location/index.html



回答2:

Here is application that does something like you want:

https://github.com/sergstetsuk/CosyDVR/blob/master/src/es/esy/CosyDVR/CosyDVR.java

Main Activity starts on BackgroundVideoRecorder service.

Intent intent = new Intent(/*CosyDVR.this*/getApplicationContext(), BackgroundVideoRecorder.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startService(intent);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);

look at mConnection onServiceConnected,onServiceDisconnected.

Here is BackgroundVideoRecorder class:

https://github.com/sergstetsuk/CosyDVR/blob/master/src/es/esy/CosyDVR/BackgroundVideoRecorder.java

It implements LocationListener. So has onLocationChanged, onProviderDisabled, onProviderEnabled, onStatusChanged.