为什么我的 WorkManager 工作线程没有在 onDestroy 中被触发?

问题描述 投票:0回答:1

我面临着从 MainActivity 的 onDestroy 方法触发 WorkManager 工作线程的问题。这是场景:

我使用 WorkManager 实现了 ClearCacheWorker 来在应用程序关闭时处理后台任务。我在 onDestroy 方法中安排这个工作进程,如下所示:


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

ClearCacheScheduler 看起来像这样:

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

但是,当我关闭应用程序时,会调用 onDestroy 方法(通过日志验证),但不会触发 ClearCacheWorker 的 doWork() 。这是我的工作实现:


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

我已经查过了:

  1. 应用程序关闭时,onDestroy 方法会正确记录。

  2. scheduleClearCache方法正在被触发

问题:

  1. 从 onDestroy 调用时 WorkManager 不启动工作进程是否有原因?

  2. 这是否与应用程序的进程在 WorkManager 排队或执行工作之前被终止有关?

  3. 在onStop或其他生命周期方法中调度worker会更可靠吗?

任何见解或建议将不胜感激!

预先感谢您的帮助!

android android-lifecycle android-workmanager android-background ondestroy
1个回答
0
投票

如果我没记错的话,当应用程序被销毁时,不能保证在 onDestroy() 期间安排的 WorkManager 任务将会执行,因为在 WorkManager 可以正确初始化和执行工作请求之前,该进程可能会终止。

我相信将逻辑移至 onStop() 生命周期方法可能是更好的选择,因为它可以为您的应用程序提供更多时间将工作人员提交到工作人员数据库。我相信当应用程序不再对用户可见但在系统销毁之前会调用 onStop() 。

如果我错了,其他人可以插话,我会很乐意编辑我的答案。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.