gpt4 book ai didi

java - 如何修复[发现 : 'android.content.Context' , 需要 : 'androidx.lifecycle.LifecycleOwner' ] in BroadcastReceiver?

转载 作者:行者123 更新时间:2023-12-01 21:55:02 28 4
gpt4 key购买 nike

这不是重复的,因为我的问题是第一个参数类型错误。找到:'android.content.Context',必需:'androidx.lifecycle.LifecycleOwner',但我没有得到任何解决此问题的答案。我正在尝试在后台服务中实现工作管理器。

我尝试将其转换为 AppCompatActivity、LifeCycleOwner 等,但它本身也不起作用...

这是代码:

Constraints constraints = new Constraints.Builder()
.setRequiresCharging(true)
.build();

final Data data = new Data.Builder()
.putDouble(USER_LAT, maps.get(i).getUser_lat())
.putDouble(USER_LNG, maps.get(i).getUser_lng())
.putLong(MAP_ID, id)
.putString(METHOD, maps.get(i).getMethod())
.putString(STATUS, maps.get(i).getStatus())
.putString(RECIEVED_DATA, maps.get(i).getCreate_time())
.build();

final OneTimeWorkRequest oneTimeWorkRequest = new OneTimeWorkRequest.Builder(DatabaseToApiWorker.class)
.setInputData(data)
.setConstraints(constraints)
.setInitialDelay(delay, TimeUnit.SECONDS)
.build();

WorkManager.getInstance().enqueue(oneTimeWorkRequest);
WorkManager.getInstance().getWorkInfoByIdLiveData(oneTimeWorkRequest.getId())
.observe((LifecycleOwner) context, new Observer<WorkInfo>() {
@Override
public void onChanged(WorkInfo workInfo) {
if (workInfo != null)
Log.e("ServiceWorker",workInfo.getState().name());
if (workInfo.getState().isFinished())
{
if (workInfo.getState() == WorkInfo.State.SUCCEEDED){

Data data1 = workInfo.getOutputData();
Long id = data1.getLong(DatabaseToApiWorker.MAP_ID_WORKER,0);
appDatabase.getMapDAO().deleteIt(id);
Log.e("ServiceWorker", String.valueOf(id));
} else if (workInfo.getState() == WorkInfo.State.FAILED) {

Log.e("ServiceWorker", String.valueOf(id)+" Sending Failed");
}

} else {

Log.e("WORKER", String.valueOf(id)+" Failed");
}
}
});

最佳答案

所以我发现我的问题的解决方案是实现一个自定义的lifecyclerOwner,这里是 link .

这是代码:添加实现:

public class MyLocationService extends BroadcastReceiver implements LifecycleOwner {
private LifecycleRegistry lifecycleRegistry;

在 OnReceive 添加:

    lifecycleRegistry = new LifecycleRegistry(this);
lifecycleRegistry.markState(Lifecycle.State.CREATED);

将以下内容添加到您的类(class)中:

@NonNull
@Override
public Lifecycle getLifecycle() {
return lifecycleRegistry;
}

然后将上下文更改为 this::getLifecycle

关于java - 如何修复[发现 : 'android.content.Context' , 需要 : 'androidx.lifecycle.LifecycleOwner' ] in BroadcastReceiver?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58747173/

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