这不是重复的,因为我的问题是Wrong 1st argument type. Found: 'android.content.Context', required: '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 ADD中:

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


将以下内容添加到您的课程中:

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


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

08-07 22:12