Android 生命周期架构组件使用方法
SupportLibrary26.1+直接支持生命周期架构组件。使用该组件,Android生命周期的梦魇已经成为过去。再也不用担心出现CannotperformthisactionafteronSaveInstanceState这样的异常了。
笔者封装了一个简化使用该组件的辅助类,大约70行代码:
publicclassLifecycleDelegateimplementsLifecycleObserver{
privateLinkedListtasks=newLinkedList<>();
privatefinalLifecycleOwnerlifecycleOwner;
publicLifecycleDelegate(LifecycleOwnerlifecycleOwner){
this.lifecycleOwner=lifecycleOwner;
lifecycleOwner.getLifecycle().addObserver(this);
}
publicvoidscheduleTaskAtStarted(Runnablerunnable){
if(getLifecycle().getCurrentState()!=Lifecycle.State.DESTROYED){
assertMainThread();
tasks.add(runnable);
considerExecute();
}
}
@OnLifecycleEvent(Lifecycle.Event.ON_ANY)
voidonStateChange(){
if(getLifecycle().getCurrentState()==Lifecycle.State.DESTROYED){
tasks.clear();
getLifecycle().removeObserver(this);
}else{
considerExecute();
}
}
voidconsiderExecute(){
if(isAtLeastStarted()){
for(Runnabletask:tasks){
task.run();
}
tasks.clear();
}
}
booleanisAtLeastStarted(){
returngetLifecycle().getCurrentState().isAtLeast(Lifecycle.State.STARTED);
}
privateLifecyclegetLifecycle(){
returnlifecycleOwner.getLifecycle();
}
privatevoidassertMainThread(){
if(!isMainThread()){
thrownewIllegalStateException("youshouldperformthetaskatmainthread.");
}
}
staticbooleanisMainThread(){
returnLooper.getMainLooper().getThread()==Thread.currentThread();
}
}
在Activity或Fragment中这样使用
privateLifecycleDelegatelifecycleDelegate=newLifecycleDelegate(this);
然后在适当的时机调用lifecycleDelegate.scheduleTaskAtStarted
该辅助类会检查是否在主线程调用,以确保线程安全以及在主线程更新UI。
总结
以上所述是小编给大家介绍的Android生命周期架构组件使用方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。