0

I am creating a test app where it increments the value stored in the database every 5 seconds irrespective of whether the app is running or not. So because of this I opted for PeriodicWork Request but the increment happens only when the app is running and not when the app is killed or not running.

Here is my code of Worker class

public class MuWorker extends Worker {
    public int inValue;
    DatabaseAccess databaseAccess;

    public MuWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
        super(context, workerParams);
    }

    @NonNull
    @Override
    public Result doWork() {

        databaseAccess = DatabaseAccess.getInstance(getApplicationContext());
        databaseAccess.open();
        inValue = databaseAccess.readValue();
        databaseAccess.close();

        inValue=inValue+1;
        databaseAccess=DatabaseAccess.getInstance(getApplicationContext());
        databaseAccess.open();
        databaseAccess.updateValue(inValue);
        databaseAccess.close();

        return Result.success();
    }

}

Here is my code of Mainactivity

public class MainActivity extends AppCompatActivity {

    TextView t1;
    DatabaseAccess databaseAccess;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        WorkManager mWorkManager = WorkManager.getInstance();

        final PeriodicWorkRequest periodicWorkRequest
                = new PeriodicWorkRequest.Builder(MuWorker.class, 4, TimeUnit.SECONDS)
                .build();

        int value = 0;

        databaseAccess = DatabaseAccess.getInstance(getApplicationContext());
        databaseAccess.open();
        value = databaseAccess.readValue();
        databaseAccess.close();

        t1 = findViewById(R.id.text);
        t1.setText("" + value);

        mWorkManager.enqueue(periodicWorkRequest);
    }
}
Gautam
  • 1
  • 1
  • The minimum interval for a PeriodicWorkRequest is 15 minutes. This is dictated by the JobScheduler API that is used by WorkManager on API 23+. If you want to do something every 5 seconds, you're better off with a foreground services handling the period in your code. – pfmaggi Dec 24 '19 at 20:11
  • @pfmaggi Thanks that solves it. – Gautam Dec 24 '19 at 22:15

1 Answers1

0

Please also take a look at this post. In these brands because of lots of customization in operating system, by default all foreground services and work manager are not working when the app is killed. I had the same problem, and after lots of research, finally I found the solution. You must enable auto-start for your application to be able to perform when it is killed. So you must prompt the user to enable the setting. In the post, there are required Intents with proper actions you must fire in each brand.

Behrad Ranjbar
  • 261
  • 2
  • 13