国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統 > Android > 正文

Android 生命周期架構組件使用方法

2019-10-22 18:15:14
字體:
來源:轉載
供稿:網友

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 生命周期架構組件使用方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對VEVB武林網網站的支持!


注:相關教程知識閱讀請移步到Android開發頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 元氏县| 保靖县| 塔城市| 河间市| 通城县| 团风县| 湟源县| 泾阳县| 张家界市| 仲巴县| 墨江| 三原县| 宁明县| 始兴县| 偃师市| 本溪市| 西乌珠穆沁旗| 临清市| 新丰县| 聂荣县| 阜新市| 黄浦区| 兖州市| 唐海县| 清水县| 花莲市| 吴江市| 梁山县| 新宾| 遵义县| 肥城市| 潞城市| 定襄县| 米林县| 平舆县| 晋宁县| 永寿县| 鲁山县| 仪征市| 白城市| 苏尼特右旗|