我正在尝试使用lifeCycleOwner和lifecycleObserve。当我调用 lifecycleOwner.getLifecycle()。addObserver(this);
时,出现以下异常invalid parameter type. Must be one and instanceof LifecycleOwner
如下所示的代码
public class TestActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_activity);
new TestObserver(this,this);
}
}
public class TestObserver implements LifecycleObserver{
public TestObserver(LifecycleOwner lifecycleOwner, Context context){
lifecycleOwner.getLifecycle().addObserver(this);
}
}
已编辑: 根据要求Build.gradle文件
apply plugin: 'com.android.application'
android {
compileSdkVersion 27
defaultConfig {
applicationId "com.example.test"
minSdkVersion 14
targetSdkVersion 27
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
multiDexEnabled true
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.android.support:design:27.1.1'
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support:cardview-v7:27.1.1'
implementation 'com.android.support.constraint:constraint-layout:1.1.2'
// ViewModel and LiveData ,lifecycleObserver
implementation 'android.arch.lifecycle:extensions:1.1.1'
implementation "android.arch.lifecycle:runtime:1.1.1"
}
apply plugin: 'com.google.gms.google-services'
apply plugin: 'io.fabric'
答案 0 :(得分:5)
在LifecycleObserver中重写onCreate或其他事件时,请勿将任何参数传递给该方法。
这会导致您的错误:
let errors = {
location: {
coordinates: []
}
}
这是正确的声明:
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
protected void onCreate(Bundle savedInstanceState)
答案 1 :(得分:0)
这是您的观察员类别:
public class TestObserver implements LifecycleObserver {
private Activity activity;
public void ActivityRecognitionHelper(LifecycleOwner lifecycleOwner, Activity activity){
this.activity = activity;
lifecycleOwner.getLifecycle().addObserver(this);
}
}
您可以通过以下方式从任何活动中调用上述“观察者类”:
new TestObserver().ActivityRecognitionHelper(this, this);
答案 2 :(得分:0)
标记的答案不正确。
允许将类型为LifecycleOwner
的参数作为第一个参数。可选,可以添加Lifecycle.Event
作为第二自变量。在第二种情况下,注释必须为Lifecycle.Event.ON_ANY
。这两个有效选项:
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
private fun onCreate(owner: LifecycleOwner) {}
@OnLifecycleEvent(Lifecycle.Event.ON_ANY) // << Must be ON_ANY
private fun onAnyEvent(owner: LifecycleOwner, event: Lifecycle.Event) {}