WorkManager PeriodicWorkRequest run twice - android

I have an app that runs a database refresh every 15 mins.
The PeriodicWorkRequest is enqueued in onCreate of my main activity.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
updateDatabasePeriodically();
public void updateDatabasePeriodically() {
PeriodicWorkRequest updateDatabaseRequest =
new PeriodicWorkRequest.Builder(UpdateDatabaseWorker.class, 15, TimeUnit.MINUTES).build();
WorkManager.getInstance(getMainActivityContext()).enqueue(updateDatabaseRequest);
}
UpdateDatabaseWorker:
#Override
public Result doWork() {
// Do the work here--in this case, upload the images.
updateDatabase();
// Indicate whether the task finished successfully with the Result
return Result.success();
}
private void updateDatabase() {
AppDatabase appDatabase = AppDatabase.getInstance(context);
Log.i(TAG, "Updating alerts at: " + DateTimeHelper.getHumanReadableTime(now));
}
The problem is that the work is done twice every time the job executes as can be seen by my log statements
2019-11-22 10:20:23.185 24987-25085/com.package.myapp I/com.package.myapp.UpdateDatabaseWorker: Updating at: 22/11/2019 10:20:23
2019-11-22 10:21:30.510 25309-25408/com.package.myapp I/com.package.myapp.UpdateDatabaseWorker: Updating at: 22/11/2019 10:21:30
2019-11-22 10:34:49.642 25309-26180/com.package.myapp I/com.package.myapp.UpdateDatabaseWorker: Updating at: 22/11/2019 10:34:49
2019-11-22 10:35:23.372 25309-26198/com.package.myapp I/com.package.myapp.UpdateDatabaseWorker: Updating at: 22/11/2019 10:35:23
Why is this happening? Should I be creating the request somewhere else?
Would this be a good solution? https://stackoverflow.com/a/53059601/9137086
I feel like that's a treating the symptom instead of the disease

In this cases please, use an uniqueWorkRequest, otherwise (especially for PeriodicWorkRequest) you will end up with duplicates.
public void updateDatabasePeriodically() {
PeriodicWorkRequest updateDatabaseRequest =
new PeriodicWorkRequest.Builder(UpdateDatabaseWorker.class, 15, TimeUnit.MINUTES).build();
WorkManager.getInstance(getMainActivityContext())
.enqueueUniquePeriodicWork("uniqueWorkName",
ExistingPeriodicWorkPolicy.KEEP,
updateDatabaseRequest);
}
You can take a look at the reference for WorkManager#enqueueUniqueWork for more information on the call and on the ExistingPeriodicWorkPolicy one to see which are the options.
If you don't have requirements to use REPLACE, please use KEEP, it's less expensive and avoid stopping an already working Work.

Related

Writing Firebase database after app is swiped from recent list

I need to write three items of data in Firebase Realtime Database in case the user kill the app
from recent list while it's still running; I implemented a service in order to
update the database when onTaskRemoved is called.
In the manifest the service is declared with the option android:stopWithTask="false"
Here is the service
public class ServiceAppMonitoring extends Service {
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_NOT_STICKY;
}
#Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
FirebaseDatabase mDatabase = FirebaseDatabase.getInstance();
SharedPreferences mSettings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
//Get some datas from Shared Preferences...
String path1 = "first/node/path";
mDatabase.getReference(path1).setValue(false);
if (condition) {
// Compose array of datas
List<Object> data2 = Arrays.asList(new Object[]{ ... });
String path2 = "second/node/path";
mDatabase.getReference(path2).setValue(data2);
// Compose array of datas
List<Object> data3 = Arrays.asList(new Object[]{ ... });
String path3 = "third/node/path";
mDatabase.getReference(path3).setValue(data3);
stopSelf();
} else {
stopSelf();
}
}
#Nullable
#Override
public IBinder onBind(Intent intent) { return null; }
}
Strangely only the first instruction is successful, the other two seem to be ignored... at least no data is written into database.
Further I've noticed another "unusual" behaviour, if I arrange all the DatabaseReferences in the
following way:
mDatabase.getReference("first").child("node").child("path").setValue(false);
no one of the instructions end up writing into database, to get (at least) the first one working I've to arrange this way:
mDatabase.getReference("first/node/path").setValue(false);
Can anybody kindly help me to understand why this happens?
Thanks
This is almost certainly because Firebase operations are asynchronous, and return immediately before the writes are complete. onTaskRemved is going to return before either of the database writes fully finish.
I'm guessing that your app process is going to die very soon, if not immediately, after onTaskRemved returns. This means that your database writes might not finish. Android doesn't know that these writes are pending, and it's not going to wait for them.
Since you don't have way from your service to tell Android to wait for these writes, you will have to schedule them for later. I suggest looking into using WorkManager to schedule the writes to happen in the background, whenever Android allows it. It might not be immediate, but WorkManager will make sure that any scheduled tasks will eventually complete.
Hey based on your answer I updated a small thing on database from onTaskRemoved like this
I already initialized the DatabaseReference in the onCreate method
DatabaseReference temp = FirebaseDatabase.getInstance.getReference().child("temp");
and in onTaskRemoved
temp.setValue(true);
this is getting executed and I added a onchange listener in onCreate method to listen for this values change and it worked like a charm. If you don't understand anything feel free to ask and let me know how you got over this problem:)
EDIT:
This is not working in all devices...
EDIT AGAIN: I simply used on Destroy method in my service and killed the service after completing the task and is working for now...
EDIT AGAIN AND AGAIN: OnDestroy is not working in android 6 or below I guess. I tested in Android 6 and it didnt work.

In Android run asyn task inside Worker class of WorkManager

I've a Worker in which i first want to apply FFMPEG command before uploading it to server. As Worker is already running in background so to keep the result on hold until file uploads I've used RxJava .blockingGet() method. But I'm unable to understand that how to execute FFmpeg command synchronously by anyway i.e. RxJava etc. One tip that I found is to use ListenableWorker but it's documentation says that it stops working after 10 minutes. So, i don't want to go with that solution. Following is the method of FFmpeg just like any other async method. How can i make it synchronous or integrate it with RxJava? Any ideas would be appreciable.
ffmpeg.execute(command, new ExecuteBinaryResponseHandler() {
#Override
public void onFailure(String s) {
}
#Override
public void onSuccess(String s) {
uploadMediaItem(mediaUpload);
}
#Override
public void onProgress(String s) {
}
#Override
public void onStart() {
}
#Override
public void onFinish() {
// countDownLatch.countDown();
}
});
This is the flow of my Worker:
check pending post count in DB.
Pick first post and check if it has pending media list to upload.
Pick media recursively and check if editing is required on it or not.
Apply FFmpeg editing and upload and delete from DB.
Repeat the cycle until last entry in the DB.
Thanks
If you wanna create a syncronous job you need to use the CountDownLatch class (there is a comment in your code).
CountDownLatch is a syncronization object that can be used in cases like this.
As for now there isn't a valid method to have sync workers.
Listenable workers is useful when you want to monitor the worker itself from your app using a Livedata that return useful information (e.g. the status).
If I remember correctly the standard Worker class also descend from Listenable worker so you can use that.
In your case is useful to have two workers: the first apply a FFMPEG command, and the second worker that take the output of this command to do the network upload. Separating this two operations allows you to have more time for complete the two works (10 + 10).
In your case you can do something like this for the first worker:
private final CountDownLatch syncLatch = new CountDownLatch(1);
...ctor
doWork(){
//your asyncronous call
...
#Override
public void onFinish() {
//you need to save error status into a onSuccess and onFailure
syncLatch.countDown();
}
...
//end
syncLatch.await();
...
//evaluate if there are errors
...
//create output to pass to the next worker
Data outputData = ...
//pass the result to second worker, remember that onfailure will stop all subsequent workers
if(error==true)
{
return Result.failure(outputData);
}else{
return Result.success(outputData);
}
}
For the second worker you can do the same according to your upload function behavihour to syncronize the call.
Hope this help.
Cheers.

WorkManger in Android is executing doWork() more than once

I am using WorkManager to schedule some tasks but the problem is that work manager is executing those tasks { doWork() } more than once in a single call.
I am using:
'android.arch.work:work-runtime:1.0.0-alpha08'
I have tried using -alpha07,06,05,04. But I have same issue. Sometimes it even executes 5-6 times at once
Here is the code:
public class MyWorker extends Worker {
#NonNull
#Override
public Result doWork() {
Log.i("CountWorker","0");
sendNotification("Notice", "A notice was sent");
return Result.SUCCESS;
}
This is the Activity
public class MyWorkerActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final PeriodicWorkRequest pwr = new PeriodicWorkRequest
.Builder(MyWorker.class, 16, TimeUnit.MINUTES)
.setConstraints(Constraints.NONE)
.build();
WorkManager.getInstance().enqueue(pwr);
}
}
This is the result from Logcat:
09-24 16:44:35.954 22779-22816/com.simran.powermanagement I/CountWorker: 0
09-24 16:44:35.970 22779-22817/com.simran.powermanagement I/CountWorker: 0
09-24 16:44:35.977 22779-22818/com.simran.powermanagement I/CountWorker: 0
When you enqueue a PeriodicWorkRequest, that does not cancel any existing PeriodicWorkRequest that you have previously enqueued. Therefore as you have written your app, every time your activity starts, you add yet periodic work request, slowly going from 1 to 2 to 3 onward.
You instead want to use enqueueUniquePeriodicWork():
This method allows you to enqueue a uniquely-named PeriodicWorkRequest, where only one PeriodicWorkRequest of a particular name can be active at a time. For example, you may only want one sync operation to be active. If there is one pending, you can choose to let it run or replace it with your new work. The uniqueWorkName uniquely identifies this PeriodicWorkRequest.
With code such as:
final PeriodicWorkRequest pwr = new PeriodicWorkRequest
.Builder(MyWorker.class, 16, TimeUnit.MINUTES)
.setConstraints(Constraints.NONE)
.build();
WorkManager.getInstance().enqueueUniquePeriodicWork(
"my_worker",
ExistingPeriodicWorkPolicy.REPLACE,
pwr);
For OneTimeWorkRequest using version 1.0.0-beta01
WorkManager.getInstance()
.beginUniqueWork("Unique", ExistingWorkPolicy.KEEP, oneTimeWorkRequest)
.enqueue();
Cancel the existing sequence and REPLACE it with the new one.
KEEP the existing sequence and ignore your new request.
APPEND your new sequence to the existing one, running the new sequence's first task after the existing sequence's last task finishes
Official Documentation. https://developer.android.com/topic/libraries/architecture/workmanager/advanced

Android JobScheduler onStartJob called multiple times

The JobScheduler calls onStartJob() multiple times, although the job finished. Everything works fine, if I schedule one single job and wait until it has finished. However, if I schedule two or more jobs with different IDs at the same time, then onStartJob() is called again after invoking jobFinished().
For example I schedule job 1 and job 2 with exactly the same parameters except the ID, then the order is:
onStartJob() for job 1 and job 2
Both jobs finish, so jobFinished() is invoked for both of them
After that onStartJob() is called again for both jobs with the same ID
My job is very basic and not complicated.
public class MyJobService extends JobService {
#Override
public boolean onStartJob(final JobParameters params) {
new Thread(new Runnable() {
#Override
public void run() {
try {
// do something
} finally {
// do not reschedule
jobFinished(params, false);
}
}
}).start();
// yes, job running in the background
return true;
}
#Override
public boolean onStopJob(JobParameters params) {
// mark my background task as stopped
// do not reschedule
return false;
}
}
I schedule the jobs like this
JobInfo jobInfo = createBaseBuilder(request)
.setMinimumLatency(2_000L)
.setOverrideDeadline(4_000L)
.setRequiresCharging(false)
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
.build();
int scheduleResult = mJobScheduler.schedule(jobInfo);
// is always success
I don't know what's wrong.
I guess it's caused by the pending Job, so I call mJobScheduler.cancelAll() after the service started, problem resolved.
I think this relates to the Android bug reported here, which has apparently been fixed for Android N but will be present in earlier versions.
The OP is using a setOverrideDeadline(). My understanding of the issue reported in the linked post above is that if the job is running when the override deadline fires, it causes the job to be scheduled to run again.
So the advice is to ensure that the override fires either before the job is scheduled (not sure how that is achieved) or after it has finished. Neither seems particularly satisfactory, but at least it seems to have been fixed in Android N.
this is the problem in android lollypop and Marshmallow. It is fixed in Nougat as explained by Matthew Williams here

Job manager in Android

I have a task to run several different jobs in Android app. Each job is long-running and cosumes network, database and file system much. Each job can be run manually by user or scheduled by AlarmManager. It is very important that each job runs till the end, so it needs to continue running after user leaves the app, or even when user does not open the app at all. Jobs have some ID attribute like this:
class Job {
int id;
}
I need this hypothetical JobManager to receive jobs and sort them by ID. If a job with id = 1 is already running, then JobManager should skip all the subsequent jobs with id = 1 until this job is finished. But if a job is submitted with id = 2, then it is accepted and can be run in parallel with the first job.
The jobs should also to keep wake lock until completed, like it is done in CommonsWare's WakefulIntentService.
I have several ideas how to implement this, but all have their drawbacks:
Subclass of the Service class that runs always in background and is automatically restarted, when killed for some reason. Drawbacks: it consumes resources even if not running anything, it is running on UI thread, so we have to manage some threads that can be killed by system as usual, each client has to start the Service and nobody knows, when to stop it.
WakefulIntentService from CommonsWare. Drawbacks: because it is IntentService, it runs only sequentially, so it cannot check for existing running job.
Boolean "running" flag in the database for each job. Check it every time we want to run a job. Drawbacks: too many requests to db, difficult to implement properly, sometimes 2 equal jobs still can run in parallel, not sure about flags staying "true" in case of any unexpected error.
Existing library disigned for this purpose. As for now except CWAC-Wakeful I have found:
Robospice: https://github.com/stephanenicolas/robospice
Android Job Queue: https://github.com/path/android-priority-jobqueue
but still I don't know, how to use these libraries to run exactly one centralized service, that whould accept jobs from any other Activity, Service, BroadcastReceiver, AlarmManager, etc, sort them by ID and run in parallel.
Please advise me what solution can be used in this case.
UPDATE: See below my own solution. I'm not sure, if it works in all possible cases. If you are aware of any problems that may arise with this, please comment.
This seems to be suited for the new JobScheduler API on Lollipop, then you will have to make a wrapper around it to implement all the features that the sdk implementation is missing.
There is a compat library if you need to implement this on versions below Lollipop.
If anybody faces the same problem, here is the solution I came up with. I used Robospice lib, because it is the most robust way of running some jobs on a Service and syncing results back to the Activity. As I did not find any ways to use this lib with WakeLocks, I extended 2 classes: SpiceManager and SpiceRequest. The new classes, WakefulSpiceManager and WakefulSpiceRequest, actually borrow CommonsWare's ideas about WakeLocks, the implementation is very similar.
WakefulSpiceManager:
public class WakefulSpiceManager extends SpiceManager {
private static final String NAME = "WakefulSpiceManager";
private static volatile PowerManager.WakeLock wakeLock;
private Context context;
public WakefulSpiceManager(Context context, Class<? extends SpiceService> spiceServiceClass) {
super(spiceServiceClass);
this.context = context;
start(context);
}
private static synchronized PowerManager.WakeLock getLock(Context context) {
if (wakeLock == null) {
PowerManager mgr = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
wakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, NAME);
wakeLock.setReferenceCounted(true);
}
return wakeLock;
}
public <T> void execute(WakefulSpiceRequest<T> request, RequestListener<T> requestListener) {
PowerManager.WakeLock lock = getLock(context);
lock.acquire();
request.setLock(lock);
// explicitly avoid caching
super.execute(new CachedSpiceRequest<T>(request, null, ALWAYS_EXPIRED), requestListener);
}
}
WakefulSpiceRequest:
public abstract class WakefulSpiceRequest<R> extends SpiceRequest<R> {
private PowerManager.WakeLock lock;
public WakefulSpiceRequest(Class<R> clazz) {
super(clazz);
}
public void setLock(PowerManager.WakeLock lock) {
this.lock = lock;
}
#Override
public final R loadDataFromNetwork() throws Exception {
try {
return execute();
} finally {
if (lock.isHeld()) {
lock.release();
}
}
}
public abstract R execute() throws Exception;
}
So basically here we acquire the lock every time we are going to send a request from WakefulSpiceManager. After that the lock is passed to the WakefulSpiceRequest. When request finishes its work, it cleans the lock with release() method - this will happen even if the activity with WakefulSpiceManager is already destroyed.
Now we use those classes in usual Robospice's manner, with the only exception that we need to pass only WakefulSpiceRequests to execute on WakefulSpiceManager:
WakefulSpiceManager manager = new WakefulSpiceManager(context, MyService.class);
manager.execute(new WakefulSpiceRequest<MyResult>(MyResult.class) {
#Override
public MyResult execute() throws Exception {
return ...
}
}, new RequestListener<MyResult>() {
#Override
public void onRequestFailure(SpiceException e) {
...
}
#Override
public void onRequestSuccess(MyResult result) {
...
}
});
The new Workmanager will help you schedule tasks in any order you want. You can easily set constraints to the job that you want to be en-queued along with many other advantages over JobScheduler API or alarm manager. Have a look at this video for a brief intro - https://www.youtube.com/watch?v=pErTyQpA390 (WorkManager at 21:44).
EDIT: Updated my ans to show the capabilities of the new API
You will not need ids to handle the jobs with this one. You can simply enqueue the task and the rest will be handled by the API itself.
Some work case scenarios are
WorkManager.getInstance()
.beginWith(workA)
// Note: WorkManager.beginWith() returns a
// WorkContinuation object; the following calls are
// to WorkContinuation methods
.then(workB)
.then(workC)
.enqueue();
WorkManager.getInstance()
// First, run all the A tasks (in parallel):
.beginWith(workA1, workA2, workA3)
// ...when all A tasks are finished, run the single B task:
.then(workB)
// ...then run the C tasks (in any order):
.then(workC1, workC2)
.enqueue();

Categories

Resources