今天就跟大家聊聊有關如何在Android中使用生命周期架構組件,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結了以下內容,希望大家根據(jù)這篇文章可以有所收獲。
Support Library 26.1+ 直接支持生命周期架構組件。使用該組件,Android 生命周期的夢魘已經(jīng)成為過去。再也不用擔心出現(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);
然后在適當?shù)臅r機調用 lifecycleDelegate.scheduleTaskAtStarted
該輔助類會檢查是否在主線程調用,以確保線程安全以及在主線程更新 UI。
看完上述內容,你們對如何在Android中使用生命周期架構組件有進一步的了解嗎?如果還想了解更多知識或者相關內容,請關注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝大家的支持。
當前文章:如何在Android中使用生命周期架構組件-創(chuàng)新互聯(lián)
URL標題:http://aaarwkj.com/article36/dsjisg.html
成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供Google、網(wǎng)站營銷、網(wǎng)站維護、App開發(fā)、做網(wǎng)站、自適應網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經(jīng)允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內容