不兼容的类型:MainActivity 无法转换为 LifecycleOwner

incompatible types: MainActivity cannot be converted to LifecycleOwner

MainActivity cannot be converted to LifecycleOwner 我用它作为 LiveCycle 所有者,但它被拒绝了,我得到了一个错误,如图所示。 我在 Api 25 上工作,这个问题可能与这个版本有关 这是关于我的 sdk

的信息
compileSdkVersion 25
buildToolsVersion '25.0.2'

这是我的代码:

private void retrieveTasks() {
    Log.d(TAG, "Actively retrieving the tasks from the DataBase");
    // Extract all this logic outside the Executor and remove the Executor
    // Fix compile issue by wrapping the return type with LiveData
    LiveData<List<TaskEntry>> tasks = mDb.taskDao().loadAllTasks();
    // Observe tasks and move the logic from runOnUiThread to onChanged
    tasks.observe(this, new Observer<List<TaskEntry>>() {
        @Override
        public void onChanged(@Nullable List<TaskEntry> taskEntries) {
            Log.d(TAG, "Receiving database update from LiveData");
            mAdapter.setTasks(taskEntries);
        }
    });
}

我将 LiveData 依赖项放入 Gradle

compile "android.arch.lifecycle:extensions:1.0.0"
annotationProcessor "android.arch.lifecycle:compiler:1.0.0"

如果有人知道问题的原因,请告诉我

如您所见,here LifecycleOwner 已添加到支持库 26.1.0 中。解决问题的最简单方法是升级支持库版本。

Support Library 26.1.0 及更高版本中的 Fragments 和 Activity 已默认实现 LifecycleOwner 接口

但是在版本 25 中你需要实现 LifecycleOwner 接口 例如

public class MyActivity extends Activity implements LifecycleOwner {
    private LifecycleRegistry mLifecycleRegistry;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

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

    @Override
    public void onStart() {
        super.onStart();
        mLifecycleRegistry.markState(Lifecycle.State.STARTED);
    }

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

来源:Handling lifecycles with lifecycle-aware components

有同样的错误。升级到 androidx 支持库解决了这个问题。 在 Android Studio 中选择:Refactor -> Migrate to android x