3

Workmanager doesnt send coordinates to my server when phone is in sleepmode. Asynctask get killed?

I use the Workmanager (PeriodicWorkRequest) to get the coordinates every 15 min. To get the coordinates i use FusedLocationClient. That works fine.... but i also want to send them to my server.

If i start sending in 'public void onComplete' (see code) i have to use an AsyncTask (Other solution??). It works, when my phone is not in sleep mode. The intention is that the sending keeps running. How can I solve this (newby, examples makes me happy :))

MainActivity Start Workmanager

 public static void scheduleWork(String tag) {
        PeriodicWorkRequest.Builder SendLocation =
                new PeriodicWorkRequest.Builder(LocationWorker.class, 15,
                        TimeUnit.MINUTES);
        PeriodicWorkRequest locationCheckWork = SendLocation.build();
        WorkManager instance = WorkManager.getInstance();
        instance.enqueueUniquePeriodicWork(tag, ExistingPeriodicWorkPolicy.KEEP , locationCheckWork);
    }

LocationWorker

@NonNull
    @Override
    public Result doWork() {
        Log.d(TAG, "onStartJob: STARTING JOB..");

        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(mContext);
        mLocationCallback = new LocationCallback() {
            @Override
            public void onLocationResult(LocationResult locationResult) {
                super.onLocationResult(locationResult);
            }
        };

        LocationRequest mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
        mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

        try {
            mFusedLocationClient
                    .getLastLocation()
                    .addOnCompleteListener(new OnCompleteListener<Location>() {
                        @Override
                        public void onComplete(@NonNull Task<Location> task) {
                            if (task.isSuccessful() && task.getResult() != null) {
                                mLocation = task.getResult();
                                Log.d(TAG, "Location : " + mLocation);

                                double latitude = mLocation.getLatitude();
                                double longitude = mLocation.getLongitude();
                                // SEND TO SERVER
                                AsyncTask.execute(new Runnable()
                                {
                                    @Override
                                    public void run() {
                                        HttpURLConnection connection;
                                        try {
                                            //Open a new URL connection
                                            connection = (HttpURLConnection) new URL(myurl)
                                                    .openConnection();

                                            //Defines a HTTP request type
                                            connection.setRequestMethod("POST");

                                            //Sets headers: Content-Type, Authorization
                                            connection.setRequestProperty("Content-Type", "application/json");
                                            connection.setRequestProperty("Accept", "application/json");
                                            connection.setRequestProperty("Authorization", "Token fab11c9b6bd4215a989c5bf57eb678");

                                            String userid= Prefs.getUserid(getApplicationContext());
                                            String compid= Prefs.getCompid(getApplicationContext());


                                            //Add POST data in JSON format
                                            JSONObject jsonParam = new JSONObject();
                                            try {
                                                jsonParam.put("latitude", latitude);
                                                jsonParam.put("longitude", longitude);
                                                jsonParam.put("userid", userid);
                                                jsonParam.put("compid", compid);
                                            } catch (JSONException e) {
                                                e.printStackTrace();
                                            }

                                            //Create a writer object and make the request
                                            OutputStreamWriter outputStream = new OutputStreamWriter(connection.getOutputStream());
                                            outputStream.write(jsonParam.toString());
                                            outputStream.flush();
                                            outputStream.close();

                                            //Get the Response code for the request

                                            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                                            String responseBody = null;
                                            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
                                                responseBody = br.lines().collect(Collectors.joining());
                                            }
                                            Log.i(TAG, "responseBody: "+responseBody);


                                            //return connection.getResponseCode();
                                        } catch (IOException e) {
                                            e.printStackTrace();
                                        }
                                    }


                                });

                                mFusedLocationClient.removeLocationUpdates(mLocationCallback);
                            } else {
                                Log.w(TAG, "Failed to get location.");
                            }
                        }
                    });
        } catch (SecurityException unlikely) {
            Log.e(TAG, "Lost location permission." + unlikely);
        }

        try {
            mFusedLocationClient.requestLocationUpdates(mLocationRequest, null);
        } catch (SecurityException unlikely) {
            //Utils.setRequestingLocationUpdates(this, false);
            Log.e(TAG, "Lost location permission. Could not request updates. " + unlikely);
        }

        return Result.SUCCESS;
    }
user3229579
  • 131
  • 2
  • 6
  • 1
    If it doesn't work only when in sleep mode are you sure its not related to the Android Doze mode where apps are put to sleep to conserve battery. Try turning off the battery optimisation on your device for your app and see if you get the same problem – Boardy Jul 24 '19 at 11:38

2 Answers2

2

PeriodicWorkRequests will get deferred during doze mode. Your work is not guaranteed to run every 15 minutes. JobScheduler could decide that it wants to run your work during maintenance intervals.

Rahul
  • 19,744
  • 1
  • 25
  • 29
1

You're using a synchronous Worker to do something asynchronous. You need to use ListenableWorker if you intend to wait for callbacks to do something in your worker: https://developer.android.com/topic/libraries/architecture/workmanager/advanced/threading

SumirKodes
  • 551
  • 2
  • 6