如何在Android中使用生命周期架構(gòu)組件-創(chuàng)新互聯(lián)

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

十年的東營區(qū)網(wǎng)站建設(shè)經(jīng)驗,針對設(shè)計、前端、開發(fā)、售后、文案、推廣等六對一服務,響應快,48小時及時工作處理。營銷型網(wǎng)站的優(yōu)勢是能夠根據(jù)用戶設(shè)備顯示端的尺寸不同,自動調(diào)整東營區(qū)建站的顯示方式,使網(wǎng)站能夠適用不同顯示終端,在瀏覽器中調(diào)整網(wǎng)站的寬度,無論在任何一種瀏覽器上瀏覽網(wǎng)站,都能展現(xiàn)優(yōu)雅布局與設(shè)計,從而大程度地提升瀏覽體驗。成都創(chuàng)新互聯(lián)公司從事“東營區(qū)網(wǎng)站設(shè)計”,“東營區(qū)網(wǎng)站推廣”以來,每個客戶項目都認真落實執(zhí)行。

Support Library 26.1+ 直接支持生命周期架構(gòu)組件。使用該組件,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機調(diào)用 lifecycleDelegate.scheduleTaskAtStarted

該輔助類會檢查是否在主線程調(diào)用,以確保線程安全以及在主線程更新 UI。

看完上述內(nèi)容,你們對如何在Android中使用生命周期架構(gòu)組件有進一步的了解嗎?如果還想了解更多知識或者相關(guān)內(nèi)容,請關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝大家的支持。

當前文章:如何在Android中使用生命周期架構(gòu)組件-創(chuàng)新互聯(lián)
URL標題:http://www.muchs.cn/article36/dsjisg.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供Google、網(wǎng)站營銷網(wǎng)站維護、App開發(fā)、做網(wǎng)站自適應網(wǎng)站

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

成都網(wǎng)頁設(shè)計公司