2-2、Lifcycle核心接口
作者:互联网
- 本质是观察者模式,LifecycleOwner作为被观察者,LifecycleObserver作为观察者
1、LifecycleObserver 观察者
- 观察者实现此接口
- 顶层接口,没有任何方法和属性
package androidx.lifecycle;
@SuppressWarnings("WeakerAccess")
public interface LifecycleObserver {
}
FullLifecycleObserver
- FullLifecycleObserver定义了全生命周期方法
interface FullLifecycleObserver extends LifecycleObserver {
void onCreate(LifecycleOwner owner);
void onStart(LifecycleOwner owner);
void onResume(LifecycleOwner owner);
void onPause(LifecycleOwner owner);
void onStop(LifecycleOwner owner);
void onDestroy(LifecycleOwner owner);
}
2、LifecycleOwner 被观察者
- LifecycleOwner接口只有一个方法,getLifecycle()
public interface LifecycleOwner {
/**
* Returns the Lifecycle of the provider.
*
* @return The lifecycle of the provider.
*/
@NonNull
Lifecycle getLifecycle();
}
Activity
- AppCompatActivity继承自FragmentActivity,FragmentActivity继承自ComponentActivity
- ComponentActivity实现了LifecycleOwner接口
public class ComponentActivity extends Activity
implements LifecycleOwner, KeyEventDispatcher.Component {
private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
@Override
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
}
Fragment
- Lifecycle在Fragment中的使用方法与Activity中的使用方法相同,因为Fragment也实现了LifecycleOwner接口
public class Fragment implements ComponentCallbacks, OnCreateContextMenuListener, LifecycleOwner, ViewModelStoreOwner {
@Override
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
}
service
- 创建Service时,继承LifecycleService,这个类也实现了LifecycleOwner接口
package androidx.lifecycle;
public class LifecycleService extends Service implements LifecycleOwner {
}
标签:LifecycleOwner,核心,void,接口,Lifecycle,Lifcycle,owner,public 来源: https://www.cnblogs.com/ArthurWangWang/p/14970166.html