14

I'm trying to make a worker-run every 15 minutes using the new WorkManager API, 1.0.0-alpha06. If I'm not wrong, using Work manager with PeriodicWorkRequest should make the worker outlive task kills and phone reboots, but when I swipe the task from the Recent Apps the scheduled worker is lost (I've waited for around 45 minutes to see any logs of the worker scheduled for 15 minutes interval).

these are my files:

MyExampleWorker.java:

public class MyExampleWorker extends Worker{
    public static final String TAG = "MY_EXAMPLE_WORKER";

    @NonNull
    @Override
    public Result doWork() { 
        Log.i(TAG, "Starting background worker");
        // Getting configuration data
        long param1 = getInputData().getLong("param1", 60000);
        String param2 = getInputData().getString("param2");
        String param3 = getInputData().getString("param3");

        PackageManager pckMgr = mContext.getPackageManager();
        ...
        ..
        .
        return Result.SUCCESS;
    }

}

Main.java: this method fires as soon as the app is launched

@ReactMethod
public void execute() {
    Log.i(TAG, "inside execute, setting up periodic worker in workManager");

    Data inputData = new Data.Builder()
            .putLong("param1", 60000)
            .putString("param2", "something")
            .putString("param3", "something else")
            .build();

    PeriodicWorkRequest periodicWorkRequest = new PeriodicWorkRequest
            .Builder(MyExampleWorker.class, PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS, TimeUnit.MILLISECONDS)
            .setInputData(inputData)
            .addTag(MyExampleWorker.TAG)
            .build();

    WorkManager.getInstance().enqueueUniquePeriodicWork(MyExampleWorker.TAG, ExistingPeriodicWorkPolicy.KEEP, periodicWorkRequest);
}

UPDATE: Not only that, but if I open the app once again I see the log for "inside execute, setting up a periodic worker in workManager" but seems the worker is not scheduled, it has been over an hour and no logs for the worker are present in logcat.

Am I missing something here?

Any help is GREATLY appreciated!!

Diego

Athira
  • 1,177
  • 3
  • 13
  • 35
Dieguinho
  • 758
  • 2
  • 14
  • 31
  • on which android device you are testing ?, whats compileSdk version ? – iamkdblue Aug 13 '18 at 04:52
  • Can you resolve *task id* by *TAG* after app restart? – Ufkoku Aug 13 '18 at 14:06
  • Sorry for the delays guys, I've been really busy with a alpha release. @kdblue its compileSdkVersion es 27, also its been tested on emulator running android API 27. – Dieguinho Aug 21 '18 at 01:09
  • @Ufkoku not sure how I would go about doing that... – Dieguinho Aug 21 '18 at 01:09
  • 1
    @Dieguinho I am not sure `WorkManager requires compileSdk version 28 or higher`. i read here google official page - https://developer.android.com/topic/libraries/architecture/adding-components#workmanager – iamkdblue Aug 21 '18 at 03:14
  • @kdblue ok I missed that one. In the ["WorkManager basics"](https://developer.android.com/topic/libraries/architecture/workmanager/basics) and the ["WorkManager advanced features"](https://developer.android.com/topic/libraries/architecture/workmanager/advanced) doesn't say anything about min API level =/ Thanks for the info, I also see theres a new release available, maybe its more stable... – Dieguinho Aug 23 '18 at 02:29
  • @Dieguinho : I am facing similar issue on my Asus/Redmi phones. Did you find any solution to this ? – AndroidGuy Feb 26 '20 at 10:28
  • @Dieguinho Did you get any Solution for i am also Struggling with same. – Vivek Samele May 10 '21 at 16:47
  • @VivekKumarSamele I really don't recall, but its been a while, it should be more stable with the subsequent versions of workmanager – Dieguinho May 10 '21 at 19:46

1 Answers1

9

This is the problem caused by Battery Optimization and/or Doze mode, occurs especially when you are using Chinese Rom like Oxygen OS, MIUI etc.

Test your app on Stock Rom's, this will work perfectly fine. There would be no issues at all. This is because these Chinese ROM enable their custom power saving techniques that prevent any background services from running.

Two things you can do:

  1. Use the Ignore Battery Optimization and whitelist your app. When you enable this, a user will be asked like this,

enter image description here

You can ask programmatically

    Intent intent = new Intent();
    String packageName = context.getPackageName();
    PowerManager pm = (PowerManager) 
    context.getSystemService(Context.POWER_SERVICE);
    if (pm.isIgnoringBatteryOptimizations(packageName))
        intent.setAction(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS);
    else {
      intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
      intent.setData(Uri.parse("package:" + packageName));
    }
    context.startActivity(intent);

And in your manifest

<uses-permission 
android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS"/>

This way you can whitelist your app and work manager will work, but unfortunately, Google will remove your app from their play store if you request the above permission. No one knows why!!!

Read this article on Google's Anti Trust Issues

  1. The Second method is you can ask the users to whitelist their app by not showing the above dialog. You can do this

startActivityForResult(new Intent(android.provider.Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS), 0);

Maddy
  • 4,525
  • 4
  • 33
  • 53
This Guy Codes
  • 125
  • 1
  • 4
  • 2
    this is not the case, I'm testing it on android emulator API version 27. The device does not enter Doze mode, I just kill the app from the Recent Apps menu and sometimes the task is lost, sometimes it isn't – Dieguinho Aug 21 '18 at 01:11
  • Is there a way to get callback with result for ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS intent so that when user switch off battery optimization I can start activity's methods – Ankesh kumar Jaisansaria Jun 25 '19 at 05:42
  • I testing on an Android One phone, which uses the OS as is and I am facing the same problem. So I think the problem can exist independently of the manufacturer as well. – fsljfke Sep 04 '20 at 15:09
  • 1
    @vaibhavS Have you got any solutions yet. Please help me on it, i have also stuck on the same problem – Ravindra Kushwaha Oct 26 '20 at 11:14