Location not getting called from WorkManager

笑着哭i 提交于 2021-01-29 05:39:13

问题


I am using work manager to start location services, it loads doWork() method after every 15 minutes, but does not execute onLocationChanged.

Before i was using Job Scheduler, and it was working just fine.

The following code also works fine, if i display notification from Work Manager after 15 minutes.

This is my code.

   public class LocationWorker extends Worker implements LocationListener, GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener{


        private static final long BACKGROUND_INTERVAL = 1000 * 60 * 60;
        final private String TAG = LocationUpdateService.class.getSimpleName();
        LocationRequest mLocationRequest;
        GoogleApiClient mGoogleApiClient;



 @NonNull
    @Override
    public Result doWork() {


        if (isGooglePlayServicesAvailable()) {
            mGoogleApiClient = new GoogleApiClient.Builder(GlobalApplication.getAppContext())
                    .addApi(LocationServices.API)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .build();

            mGoogleApiClient.connect();
            jwtToken = getJWTToken();
        }


        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(BACKGROUND_INTERVAL);
        mLocationRequest.setFastestInterval(BACKGROUND_INTERVAL);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);

        return null;
    }



@Override
    public void onLocationChanged(Location location) {


        String storedLat, storedLng;
        //...

}

回答1:


There are a few things that are wrong with this code:

  1. At a high level, you are using a Worker - which is synchronous - to execute an asynchronous (callback-based) piece of code. This won't work. Please read https://developer.android.com/topic/libraries/architecture/workmanager/advanced/threading (and in particular, pay attention to ListenableWorker - that's the class you want to use).

  2. You are returning null from a @NonNull method. WorkManager will immediately treat this work as failed. Return a proper value.

  3. Your location interval is set for an hour. Workers can execute for a maximum of 10 minutes, so this won't work either. FWIW, I really doubt this code was working properly with JobScheduler; it too has a 10 minute execution window.



来源:https://stackoverflow.com/questions/55795134/location-not-getting-called-from-workmanager

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