简体   繁体   中英

doWork() method of workmanager is not getting called from alarm manager receiver

I am using work manager Onetime Request to perform the task. First the alarm manager gets call in given frequency and from alarm manager receiver class, work manager class gets called. All code was working fine, but suddenly the work manager doWork is not getting called. Flow is coming till alarm manager receiver but not proceeding further.

Alarm Manager Receiver class

public class WorkAlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    final String TAG = "WorkAlarmReceiver";
    if (BuildConfig.DEBUG) {
        Log.i(TAG, "onReceive: intent=" + intent);
    }
    OneTimeWorkRequest startWork = new OneTimeWorkRequest.Builder(WorkManagerForTools.class).build();
    WorkManager.getInstance(context).enqueueUniqueWork("Validate Tool", ExistingWorkPolicy.APPEND_OR_REPLACE , startWork);

}

This Receiver is calling fine in given time interval

        //checking if alarm is working with pendingIntent
        Intent workIntent = new Intent(mContext,
                WorkAlarmReceiver.class)
                .setAction(Long.toString(System.currentTimeMillis()
        PendingIntent workPendingIntent = PendingIntent.getBroadcast(mContext, 1001,
                workIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        Log.e(TAG, "New data of pending intent: " + workSpecId + " local work id, " + localWorkId +
                " tools id list " + updatedMobileAppToolIds);
        if(BuildConfig.DEBUG) {
            Log.d(TAG, "New data of pending intent: " + workSpecId + " local work id, " + localWorkId +
                    " tools id list " + updatedMobileAppToolIds);
        }
        boolean isWorking = (PendingIntent.getBroadcast(mContext, 1001, workIntent, PendingIntent.FLAG_NO_CREATE) != null);//just changed the flag
        if (isWorking) {
            alarmManager.cancel(workPendingIntent);
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
                    10 * (minFrequency / 10), workPendingIntent);
        } else {
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
                    10 * (minFrequency / 10), workPendingIntent);
        }

The alarm manager receiver class then call workmanager class. Here is the work manager class

    @SuppressLint("WrongThread")
@NonNull
@Override
public Result doWork() {
    // Code to be execute

}

Any help on this Appreciated.

You can achieve scheduled tasks using periodic work requests. Here's how you can do it:

  • Define constraints like if device should be connected or should have sufficient battery.

  • Now create a periodic request with constraints & if required define a tag name. Also set a delay this which will set a initial delay for your work to start.

  • And create a enqueueUniquePeriodicWork by providing unique work name & the ExistingPeriodicWorkPolicy which you can read here ExistingPeriodicWorkPolicy Enum values

  • By default periodic work will take 15 minutes to execute the work request.

     Constraints constraints = new Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).setRequiresBatteryNotLow(true).build(); PeriodicWorkRequest periodicRequest = new PeriodicWorkRequest.Builder(MyWorkerClass.class, 15, TimeUnit.MINUTES) .addTag("myPeriodicRequest") .setConstraints(constraints) .setInitialDelay(5, TimeUnit.MINUTES) .build(); WorkManager.getInstance(context).enqueueUniquePeriodicWork("myPeriodicRequest", ExistingPeriodicWorkPolicy.APPEND_OR_REPLACE, periodicRequest);

You are missing the point on how the WorkManager should be used. You can be exact with AalarmManager, but then you pass your execution to something inexact - the WorkManager. So no point in using the AlarmManager at all. Just use the WorkManager directly with either Periodic Request or maybe some Trigger. You can check more here in my answer comparing the different APIs.

Background processing in modern Android

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM