今天就跟大家聊聊有關(guān)如何在Android中使用生命周期架構(gòu)組件,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。

Support Library 26.1+ 直接支持生命周期架構(gòu)組件。使用該組件,Android 生命周期的夢(mèng)魘已經(jīng)成為過(guò)去。再也不用擔(dān)心出現(xiàn) Can not perform this action after onSaveInstanceState 這樣的異常了。
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。
看完上述內(nèi)容,你們對(duì)如何在Android中使用生命周期架構(gòu)組件有進(jìn)一步的了解嗎?如果還想了解更多知識(shí)或者相關(guān)內(nèi)容,請(qǐng)關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝大家的支持。
當(dāng)前文章:如何在Android中使用生命周期架構(gòu)組件-創(chuàng)新互聯(lián)
URL標(biāo)題:http://chinadenli.net/article36/dsjisg.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供Google、網(wǎng)站營(yíng)銷、網(wǎng)站維護(hù)、App開(kāi)發(fā)、做網(wǎng)站、自適應(yīng)網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容