gpt4 book ai didi

android - 如何在后台线程上运行 ListenableWorker 工作?

转载 作者:行者123 更新时间:2023-12-01 08:45:53 27 4
gpt4 key购买 nike

由于我需要在 WorkManager 中异步执行工作,我需要使用 ListenableWorker ,默认情况下在主 (UI) 线程上运行。由于这项工作可能是一个很长的处理任务,可能会卡住界面,我想在后台线程上执行它。在 Working with WorkManager (Android Dev Summit '18) video ,Google 工程师展示了如何手动配置 WorkManager 以在自定义 Executor 上运行作品,所以我听从了他的指导:

1) 在 AndroidManifest 中禁用默认的 WorkManager 初始化程序:

<provider
android:name="androidx.work.impl.WorkManagerInitializer"
android:authorities="com.example.myapp.workmanager-init"
tools:node="remove" />

2) 在 Application.onCreate 中,使用自定义配置初始化 WorkManager,在我的例子中是这样的:
public class MyApplication extends Application {

@Override
public void onCreate() {
super.onCreate();
Configuration configuration = new Configuration.Builder().setExecutor(Executors.newSingleThreadExecutor()).build();
WorkManager.initialize(this, configuration);
}
}

现在我的实际 ListenableWorker这是:
@NonNull
@Override
public ListenableFuture<Result> startWork() {
Log.d(TAG, "Work started.");
mFuture = ResolvableFuture.create();
Result result = doWork();
mFuture.set(result);
return mFuture;
}

private Result doWork() {
Log.d(TAG, "isMainThread? " + isMainThread());
mFusedLocationProviderClient.getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
if (location != null) {
// Since I still don't know how to communicate with the UI, I will just log the location
Log.d(TAG, "Last location: " + location);
return Result.success();
} else {
return Result.failure();
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
e.printStackTrace();
return Result.failure();
}
});
}

private boolean isMainThread() {
return Looper.getMainLooper().getThread() == Thread.currentThread();
}

为什么 isMainThread()即使我指定了 Executor,方法也返回 true WorkManager 应该用作新的后台线程,我如何才能在后台线程上实际运行该工作?

编辑: ListenableWorker需要 CountDownLatch .
由于每次成功时我都需要重新安排工作( PeriodicWorkRequest 的最小间隔为 15 分钟的解决方法),我需要在前一项工作返回成功后执行此操作,否则我的行为会很奇怪。这是必需的,因为很明显, ExistingWorkPolicy.APPEND没有按预期工作。
用例是以相当频繁的时间间隔(5-10 秒)请求高精度的位置更新,即使在后台也是如此。通过短信打开和关闭,即使应用程序未运行(但未强制停止),或通过按钮(这是一个大学项目)。
public class LocationWorker extends ListenableWorker {

static final String UNIQUE_WORK_NAME = "LocationWorker";
static final String KEY_NEW_LOCATION = "new_location";
private static final String TAG = "LocationWorker";
private ResolvableFuture<Result> mFuture;
private LocationCallback mLocationCallback;
private CountDownLatch mLatch;
private Context mContext;

public LocationWorker(@NonNull final Context appContext, @NonNull WorkerParameters workerParams) {
super(appContext, workerParams);
mContext = appContext;
Utils.setRequestingLocationUpdates(mContext, true);
mLatch = new CountDownLatch(1);
mLocationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
LocationUtils.getInstance(mContext).removeLocationUpdates(this);
Location location = locationResult.getLastLocation();
Log.d(TAG, "Work " + getId() + " returned: " + location);
mFuture.set(Result.success(Utils.getOutputData(location)));
// Rescheduling work
OneTimeWorkRequest request = new OneTimeWorkRequest.Builder(LocationWorker.class).setInitialDelay(10, TimeUnit.SECONDS).build();
WorkManager.getInstance().enqueueUniqueWork(LocationWorker.UNIQUE_WORK_NAME, ExistingWorkPolicy.KEEP, request);
Log.d(TAG, "Rescheduling work. New ID: " + request.getId());
// Relase lock
mLatch.countDown();
}
};
}

@NonNull
@Override
public ListenableFuture<Result> startWork() {
Log.d(TAG, "Starting work " + getId());
mFuture = ResolvableFuture.create();
LocationUtils.getInstance(mContext).requestSingleUpdate(mLocationCallback, new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
LocationUtils.getInstance(mContext).removeLocationUpdates(mLocationCallback);
Utils.setRequestingLocationUpdates(mContext, false);
WorkManager.getInstance().cancelUniqueWork(UNIQUE_WORK_NAME);
mFuture.set(Result.failure());
// Relase lock
mLatch.countDown();
}
});
try {
mLatch.await(5L, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
return mFuture;
}
}

最佳答案

如果您想连续(即少于每 60 秒),您 绝对应该使用 foreground service不是 WorkManager,用于根据 the documentation :

deferrable, asynchronous tasks



而不是需要连续运行的东西。

但是,如果您继续错误地使用 WorkManager,则需要牢记以下几点:

您的定制 doWork方法在主线程上运行,因为根据 setExecutor() documentation :

An Executor for running Workers



具体来说,只有 Worker ListenableWorker 的子类在 Executor 提供的后台线程上运行- 不是 您的 ListenableWorker执行。

根据 ListenableWorker.startWork() documentation :

This method is called on the main thread.



因为您使用的是 ListenableWorker , 你的 startWork正如预期的那样,正在主线程上调用方法。既然你自己打电话 doWork()方法在同一个线程上,你仍然会在主线程上。

在你的情况下,你不需要关心你在哪个线程上,也不需要任何 Executor因为你调用什么线程并不重要 getLastLocation()上。

相反,您只需调用 set在您的 ResolvableFuture 上当您实际得到结果时 - 即在 onSuccess() 中或 onFailure回调。这是给 WorkManager 的信号你实际上已经完成了你的工作:
public class LocationWorker extends ListenableWorker {

static final String UNIQUE_WORK_NAME = "LocationWorker";
static final String KEY_NEW_LOCATION = "new_location";
private static final String TAG = "LocationWorker";
private ResolvableFuture<Result> mFuture;
private LocationCallback mLocationCallback;

public LocationWorker(@NonNull final Context appContext, @NonNull WorkerParameters workerParams) {
super(appContext, workerParams);
}

@NonNull
@Override
public ListenableFuture<Result> startWork() {
Log.d(TAG, "Starting work " + getId());
mFuture = ResolvableFuture.create();
Utils.setRequestingLocationUpdates(getApplicationContext(), true);
mLocationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
LocationUtils.getInstance(getApplicationContext()).removeLocationUpdates(this);
Location location = locationResult.getLastLocation();
Log.d(TAG, "Work " + getId() + " returned: " + location);
// Rescheduling work
OneTimeWorkRequest request = new OneTimeWorkRequest.Builder(LocationWorker.class).setInitialDelay(10, TimeUnit.SECONDS).build();
WorkManager.getInstance().enqueueUniqueWork(LocationWorker.UNIQUE_WORK_NAME, ExistingWorkPolicy.KEEP, request);
Log.d(TAG, "Rescheduling work. New ID: " + request.getId());

// Always set the result as the last operation
mFuture.set(Result.success(Utils.getOutputData(location)));
}
};
LocationUtils.getInstance(getApplicationContext()).requestSingleUpdate(mLocationCallback, new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
LocationUtils.getInstance(getApplicationContext()).removeLocationUpdates(mLocationCallback);
Utils.setRequestingLocationUpdates(getApplicationContext(), false);
WorkManager.getInstance().cancelUniqueWork(UNIQUE_WORK_NAME);
mFuture.set(Result.failure());
}
});
return mFuture;
}
}

关于android - 如何在后台线程上运行 ListenableWorker 工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54083654/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com