Android 生命周期架構組件使用方法
Support Library 26.1+ 直接支持生命周期架構組件。使用該組件,Android 生命周期的夢魘已經成為過去。再也不用擔心出現 Can not perform this action after onSaveInstanceState 這樣的異常了。
筆者封裝了一個簡化使用該組件的輔助類,大約 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);
然后在適當的時機調用 lifecycleDelegate.scheduleTaskAtStarted
該輔助類會檢查是否在主線程調用,以確保線程安全以及在主線程更新 UI。
總結
以上所述是小編給大家介紹的Android 生命周期架構組件使用方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網站的支持!
相關文章
Android使用Jetpack Compose開發(fā)零基礎起步教程
Jetpack Compose是用于構建原生Android UI的現代工具包。Jetpack Compose使用更少的代碼,強大的工具和直觀的Kotlin API,簡化并加速了Android上的UI開發(fā)2023-04-04Android編程滑動效果之倒影效果實現方法(附demo源碼下載)
這篇文章主要介紹了Android編程滑動效果之倒影效果實現方法,基于繼承BaseAdapter自定義Gallery和ImageAdapter實現倒影的功能,并附帶demo源碼供讀者下載參考,需要的朋友可以參考下2016-02-02