Why is my WorkManager worker not being triggered in onDestroy?

I’m facing an issue with triggering a WorkManager worker from the onDestroy method of my MainActivity. Here’s the scenario:

I’ve implemented a ClearCacheWorker using WorkManager to handle background tasks when the app is closed. I’m scheduling this worker in the onDestroy method like this:


@Override
protected void onDestroy() {
    Log.d("MainActivity", "onDestroy called");
    ClearCacheScheduler.scheduleClearCache(this);
    super.onDestroy();
}

The ClearCacheScheduler looks like this:

public class ClearCacheScheduler {
    public static void scheduleClearCache(Context context) {
        Log.d("ClearCacheScheduler", "scheduleClearCache called");
 

        OneTimeWorkRequest request = new OneTimeWorkRequest.Builder(ClearCacheWorker.class)
            
            .setInitialDelay(0, TimeUnit.SECONDS)
            .addTag("clear_cache")
            .build();

        WorkManager.getInstance(context).enqueue(request)
    }
}

However, when I close the app, the onDestroy method gets called (verified with logs), but the ClearCacheWorker’s doWork() is never triggered. Here’s my worker implementation:


public class ClearCacheWorker extends Worker {
    private static final String TAG = "ClearCacheWorker";

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

    @NonNull
    @Override
    public Result doWork() {
        Log.d(TAG, "doWork()");

        try {
            Thread.sleep(500); // Simulate delay
        } catch (InterruptedException e) {
            Log.d(TAG, "doWork() interrupted");
            return Result.success();
        }

        if (isAppInForeground(getApplicationContext())) {
            Log.d(TAG, "doWork() App is in foreground");
            return Result.success();
        }

        Log.d(TAG, "doWork() App is in background");
        Intent intent = new Intent(getApplicationContext(), ClearCacheService.class);
        intent.putExtras(new android.os.Bundle());
        getApplicationContext().startService(intent);

        return Result.success();
    }

    private boolean isAppInForeground(Context context) {
        android.app.ActivityManager activityManager =
            (android.app.ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        java.util.List<android.app.ActivityManager.RunningAppProcessInfo> processes =
            activityManager.getRunningAppProcesses();
        if (processes != null) {
            for (android.app.ActivityManager.RunningAppProcessInfo processInfo : processes) {
                if (processInfo.importance ==
                        android.app.ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND
                    && processInfo.processName.equals(context.getPackageName())) {
                    Log.d(TAG, "doWork() App in foreground");
                    return true;
                }
            }
        }
        Log.d(TAG, "doWork() App in background");
        return false;
    }
}

I’ve checked that:

  1. The onDestroy method logs properly when the app is closed.

  2. The scheduleClearCache method is being triggered

Questions:

  1. Is there a reason why WorkManager doesn’t launch the worker when called from onDestroy?

  2. Could it be related to the app’s process being killed before WorkManager can enqueue or execute the work?

  3. Would scheduling the worker in onStop or another lifecycle method be more reliable?

Any insights or suggestions would be greatly appreciated!

Thanks in advance for your help!

2

If I’m not mistaken, when an app is being destroyed, there’s no guarantee that WorkManager tasks scheduled during onDestroy() will execute, as the process may be terminated before WorkManager can properly initialize and execute the work request.

I believe that moving the logic into the onStop() lifecycle method may be a better alternative, since it could provide your app with more time to submit the worker to the workers’ database. The onStop() I believe is called when the app is no longer visible to the user but before its destruction by the system.

Others can chime in on this if I’m wrong and I’ll happily edit my answer.

I believe the issue is related to the fact that you use Activity context to create your WorkManager. And than you kill your Activity right after creating WorkManager and scheduling the job.

Try to replace it with Application context:

@Override
protected void onDestroy() {
    Log.d("MainActivity", "onDestroy called");
    ClearCacheScheduler.scheduleClearCache(this.getApplicationContext());
    super.onDestroy();
}

In general it would be a better idea to create your WorkManager instance in Dagger’s Component provide-method and use scoped context there, but in your case using application context might fix the problem.

Also if you decide to create a specific worker object for your operations, consider that it’s important to pass context directly to your custom worker constructor.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật