Android 生命周期架構(gòu)組件使用方法
Support Library 26.1+ 直接支持生命周期架構(gòu)組件。使用該組件,Android 生命周期的夢(mèng)魘已經(jīng)成為過去。再也不用擔(dān)心出現(xiàn) Can not perform this action after onSaveInstanceState 這樣的異常了。
筆者封裝了一個(gè)簡(jiǎn)化使用該組件的輔助類,大約 70 行代碼:
public class LifecycleDelegate implements LifecycleObserver {
private LinkedList<Runnable> tasks = new LinkedList<>();
private final LifecycleOwner lifecycleOwner;
public LifecycleDelegate(LifecycleOwner lifecycleOwner) {
this.lifecycleOwner = lifecycleOwner;
lifecycleOwner.getLifecycle().addObserver(this);
}
public void scheduleTaskAtStarted(Runnable runnable) {
if (getLifecycle().getCurrentState() != Lifecycle.State.DESTROYED) {
assertMainThread();
tasks.add(runnable);
considerExecute();
}
}
@OnLifecycleEvent(Lifecycle.Event.ON_ANY)
void onStateChange() {
if (getLifecycle().getCurrentState() == Lifecycle.State.DESTROYED) {
tasks.clear();
getLifecycle().removeObserver(this);
} else {
considerExecute();
}
}
void considerExecute() {
if (isAtLeastStarted()) {
for (Runnable task : tasks) {
task.run();
}
tasks.clear();
}
}
boolean isAtLeastStarted() {
return getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.STARTED);
}
private Lifecycle getLifecycle() {
return lifecycleOwner.getLifecycle();
}
private void assertMainThread() {
if (!isMainThread()) {
throw new IllegalStateException("you should perform the task at main thread.");
}
}
static boolean isMainThread() {
return Looper.getMainLooper().getThread() == Thread.currentThread();
}
}
在 Activity 或 Fragment 中這樣使用
private LifecycleDelegate lifecycleDelegate = new LifecycleDelegate(this);
然后在適當(dāng)?shù)臅r(shí)機(jī)調(diào)用 lifecycleDelegate.scheduleTaskAtStarted
該輔助類會(huì)檢查是否在主線程調(diào)用,以確保線程安全以及在主線程更新 UI。
總結(jié)
以上所述是小編給大家介紹的Android 生命周期架構(gòu)組件使用方法,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
- Android Jetpack架構(gòu)組件Lifecycle詳解
- Android Jetpack架構(gòu)組件 ViewModel詳解
- Android架構(gòu)組件Room的使用詳解
- Android架構(gòu)組件Room指南
- Android-ViewModel和LiveData使用詳解
- Android LiveData使用需要注意的地方
- Android mvvm之LiveData原理案例詳解
- Android 基于MediatorLiveData實(shí)現(xiàn)紅點(diǎn)的統(tǒng)一管理
- 詳解Android JetPack之LiveData的工作原理
- Android架構(gòu)組件LiveData使用詳解
相關(guān)文章
Android UI使用HorizontalListView實(shí)現(xiàn)水平滑動(dòng)
這篇文章主要為大家詳細(xì)介紹了Android UI使用HorizontalListView實(shí)現(xiàn)水平滑動(dòng)效果,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-01-01
Android checkbox的listView(多選,全選,反選)具體實(shí)現(xiàn)方法
由于listview的一些特性,剛開始寫這種需求的功能的時(shí)候都會(huì)碰到一些問題,重點(diǎn)就是存儲(chǔ)每個(gè)checkbox的狀態(tài)值,在這里分享出了完美解決方法:2013-06-06
Android實(shí)現(xiàn)動(dòng)態(tài)定值范圍效果的控件
這篇文中給大家分享一個(gè)Android的控件,這個(gè)控件實(shí)現(xiàn)是一個(gè)可以動(dòng)態(tài)選擇定值范圍的效果,實(shí)現(xiàn)后的效果很不錯(cuò),對(duì)大家日常開發(fā)或許有所幫助,感興趣的朋友們可以一起來看看。2016-09-09
Android Studio實(shí)現(xiàn)長(zhǎng)方體表面積計(jì)算器
這篇文章主要為大家詳細(xì)介紹了Android Studio實(shí)現(xiàn)長(zhǎng)方體表面積計(jì)算器,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-05-05

