我已经尝试过这段代码并与我一起处理旧 API 和新 API:此代码在设备重新启动时每 15 分钟执行一次服务(workmanager)。对于 AndroidManifest.xml 文件:
<receiver android:name=".WorkManagerStartReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
</receiver>
在 WorkManagerStartReceiver 类上:
public class WorkManagerStartReceiver extends BroadcastReceiver {
WorkManager mWorkManager;
@Override
public void onReceive(Context context, Intent intent) {
PeriodicWorkRequest.Builder myWorkBuilder =
new PeriodicWorkRequest.Builder(TestWorker.class,
PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS,
TimeUnit.MILLISECONDS);
PeriodicWorkRequest myWork = myWorkBuilder.build();
mWorkManager = WorkManager.getInstance(context);
mWorkManager.enqueue(myWork);
}
}
而 TestWorker.class 是扩展 Worker 的类:
public class TestWorker extends Worker {
public TestWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
super(context, workerParams);
}
@NonNull
@Override
public Result doWork() {
//your work that you want to execute here
return null;
}
}
如果您希望服务在应用程序打开时开始工作,则此代码段(在 MainActivity 上)会在应用程序打开时打开。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PeriodicWorkRequest.Builder myWorkBuilder =
new PeriodicWorkRequest.Builder(TestWorker.class,
PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS,
TimeUnit.MILLISECONDS);
PeriodicWorkRequest myWork = myWorkBuilder.build();
WorkManager.getInstance(MainActivity.this)
.enqueueUniquePeriodicWork("testworker", ExistingPeriodicWorkPolicy.KEEP, myWork);
}