Android workmanager scheduled worker lost after task killed

前端 未结 1 803
星月不相逢
星月不相逢 2020-12-28 19:33

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 PeriodicWo

相关标签:
1条回答
  • 2020-12-28 19:39

    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,

    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);

    0 讨论(0)
提交回复
热议问题