LocationClient doesn't give callback when screen light goes off but my WakefulThread is running flawlessly as expected

别说谁变了你拦得住时间么 提交于 2019-11-28 05:35:18
Sean Barbeau

If you want to listen to frequent location updates in the background (e.g., every second), you should be running your code inside a Service:

http://developer.android.com/reference/android/app/Service.html

Activities can be ended by the Android platform at any point in time in which they are not in the foreground.

When using a Service, I would recommend having the Service implement the LocationListener directly, and not a Thread inside the Service. For example, use:

public class LocListener extends Service implements com.google.android.gms.location.LocationListener, ...{

I've used this design of implementing the LocationListener directly on the Service with the LocationClient and fused location provider in my GPS Benchmark app and I can confirm that this works even when the screen is off and the app is running in the background.

If you want to listen to occasional location updates in the background (e.g., every minute) using the fused location provider, a better design is to use PendingIntents, using the LocationClient.requestLocationUpdates(Location Request, PendingIntent callbackIntent) method:

https://developer.android.com/reference/com/google/android/gms/location/LocationClient.html#requestLocationUpdates(com.google.android.gms.location.LocationRequest,%20android.app.PendingIntent)

From the above Android doc:

This method is suited for the background use cases, more specifically for receiving location updates, even when the app has been killed by the system. In order to do so, use a PendingIntent for a started service. For foreground use cases, the LocationListener version of the method is recommended, see requestLocationUpdates(LocationRequest, LocationListener).

Any previous LocationRequests registered on this PendingIntent will be replaced.

Location updates are sent with a key of KEY_LOCATION_CHANGED and a Location value on the intent.

See the Activity Recognition example for a more detailed description of using PendingIntents to get updates while running in the background:

https://developer.android.com/training/location/activity-recognition.html

Modified excerpts from this documentation are below, changed by me to be specific to location updates.

First declare the Intent:

public class MainActivity extends FragmentActivity implements
        ConnectionCallbacks, OnConnectionFailedListener {
    ...
    ...
    /*
     * Store the PendingIntent used to send location updates
     * back to the app
     */
    private PendingIntent mLocationPendingIntent;
    // Store the current location client
    private LocationClient mLocationClient;
    ...
}

Request updates as you currently are, but this time pass in the pending intent:

/*
 * Create the PendingIntent that Location Services uses
 * to send location updates back to this app.
 */
Intent intent = new Intent(
        mContext, LocationIntentService.class);

...
//Set up LocationRequest with desired parameter here
...
/*
 * Request a PendingIntent that starts the IntentService.
 */
mLocationPendingIntent =
        PendingIntent.getService(mContext, 0, intent,
        PendingIntent.FLAG_UPDATE_CURRENT);
/*
 * Request location updates
 */
mLocationClient.requestLocationUpdates(mLocationRequest, callbackIntent);

Handle Location Updates

To handle the Intent that Location Services sends for each update interval, define an IntentService and its required method onHandleIntent(). Location Services sends out ... updates as Intent objects, using the the PendingIntent you provided when you called requestLocationUpdates(). Since you provided an explicit intent for the PendingIntent, the only component that receives the intent is the IntentService you're defining.

Define the class and the required method onHandleIntent():

/**
 * Service that receives Location updates. It receives
 * updates in the background, even if the main Activity is not visible.
 */
public class LocationIntentService extends IntentService {
    ...
    /**
     * Called when a new location update is available.
     */
    @Override
    protected void onHandleIntent(Intent intent) {
        Bundle b = intent.getExtras();
        Location loc = (Location) b.get(LocationClient.KEY_LOCATION_CHANGED);
        Log.d(TAG, "Updated location: " + loc.toString());


    }
    ...
}

IMPORTANT - to be as efficient as possible, your code in onHandleIntent() should return as quickly as possible to allow the IntentService to shut down. From IntentService docs:

http://developer.android.com/reference/android/app/IntentService.html#onHandleIntent(android.content.Intent)

This method is invoked on the worker thread with a request to process. Only one Intent is processed at a time, but the processing happens on a worker thread that runs independently from other application logic. So, if this code takes a long time, it will hold up other requests to the same IntentService, but it will not hold up anything else. When all requests have been handled, the IntentService stops itself, so you should not call stopSelf().

My understanding of the IntentService design is that you can spawn Threads inside onHandleIntent() to avoid blocking other location updates via platform calls to onHandleIntent(), just be aware that the Service will continue to run until all the running threads terminate.

I've spent days trying to get WiFi and cell-based locations with locked screen with Android 6.0 on Nexus 6. And looks like the native android location service simple does not allow to do it. Once device got locked it still collects location update events for 10-15 minutes then stops to providing any of location updates.

In my case the solution was to switch from native Android location service to Google Play Services wrapper called com.google.android.gms.location: https://developers.google.com/android/reference/com/google/android/gms/location/package-summary

Yes, I know that some of Android devices lack of GMS, but for my application this is the only solution to perform.

It does not stop sending location updates even when in the background and device screen is locked.

Me personally prefer RxJava library to wrap this service into a stream (examples included): https://github.com/mcharmas/Android-ReactiveLocation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!