android.arch.lifecycle.Lifecycle类的使用及代码示例

x33g5p2x  于2022-01-24 转载在 其他  
字(10.5k)|赞(0)|评价(0)|浏览(306)

本文整理了Java中android.arch.lifecycle.Lifecycle类的一些代码示例,展示了Lifecycle类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Lifecycle类的具体详情如下:
包路径:android.arch.lifecycle.Lifecycle
类名称:Lifecycle

Lifecycle介绍

[英]Defines an object that has an Android Lifecycle. android.support.v4.app.Fragment Fragment and android.support.v4.app.FragmentActivity FragmentActivity classes implement LifecycleOwner interface which has the LifecycleOwner#getLifecycle() getLifecycle method to access the Lifecycle. You can also implement LifecycleOwnerin your own classes.

Event#ON_CREATE, Event#ON_START, Event#ON_RESUME events in this class are dispatched after the LifecycleOwner's related method returns. Event#ON_PAUSE, Event#ON_STOP, Event#ON_DESTROY events in this class are dispatched before the LifecycleOwner's related method is called. For instance, Event#ON_START will be dispatched after android.app.Activity#onStart returns, Event#ON_STOP will be dispatched before android.app.Activity#onStop is called. This gives you certain guarantees on which state the owner is in.

If you use Java 8 Language, then observe events with DefaultLifecycleObserver. To include it you should add "android.arch.lifecycle:common-java8:" to your build.gradle file.

class TestObserver implements DefaultLifecycleObserver { 
 @Override 
public void onCreate(LifecycleOwner owner) { 
// your code 
} 
}

If you use Java 7 Language, Lifecycle events are observed using annotations. Once Java 8 Language becomes mainstream on Android, annotations will be deprecated, so between DefaultLifecycleObserver and annotations, you must always prefer DefaultLifecycleObserver.

class TestObserver implements LifecycleObserver { 
 @OnLifecycleEvent(ON_STOP) 
void onStopped() {} 
}

Observer methods can receive zero or one argument. If used, the first argument must be of type LifecycleOwner. Methods annotated with Event#ON_ANY can receive the second argument, which must be of type Event.

class TestObserver implements LifecycleObserver { 
 @OnLifecycleEvent(ON_CREATE) 
void onCreated(LifecycleOwner source) {} 
 @OnLifecycleEvent(ON_ANY) 
void onAny(LifecycleOwner source, Event event) {} 
}

These additional parameters are provided to allow you to conveniently observe multiple providers and events without tracking them manually.
[中]定义具有Android生命周期的对象。安卓支持v4。应用程序。碎片和安卓。支持v4。应用程序。FragmentActivity FragmentActivity类实现LifecycleOwner接口,该接口具有LifecycleOwner#getLifecycle()getLifecycle方法来访问生命周期。您还可以在自己的类中实现LifecycleOwner。
此类中的事件#ON#CREATE、事件#ON#START、事件#ON#RESUME事件在LifecycleOwner的相关方法返回后被调度。在调用LifecycleOwner的相关方法之前,将调度此类中的事件#ON_PAUSE、事件#ON_STOP、事件#ON#u DESTROY事件。例如,事件#ON_START将在android之后调度。应用程序。活动#启动返回,事件#启动停止将在android之前调度。应用程序。活动#在顶部被称为。这为您提供了所有者所处状态的某些保证。
如果使用Java 8语言,则使用DefaultLifecycleObserver观察事件。要包含它,您应该在构建中添加“android.arch.lifecycle:common-java8:”。格雷德尔档案。

class TestObserver implements DefaultLifecycleObserver { 
 @Override 
public void onCreate(LifecycleOwner owner) { 
// your code 
} 
}

如果您使用Java 7语言,则使用注释观察生命周期事件。一旦Java 8语言成为Android上的主流,注释将被弃用,因此在DefaultLifecycleObserver和注释之间,您必须始终选择DefaultLifecycleObserver

class TestObserver implements LifecycleObserver { 
 @OnLifecycleEvent(ON_STOP) 
void onStopped() {} 
}

观察者方法可以接收零个或一个参数。如果使用,第一个参数必须是LifecycleOwner类型。用Event#ON_ANY注释的方法可以接收第二个参数,该参数必须是Event类型。

class TestObserver implements LifecycleObserver { 
 @OnLifecycleEvent(ON_CREATE) 
void onCreated(LifecycleOwner source) {} 
 @OnLifecycleEvent(ON_ANY) 
void onAny(LifecycleOwner source, Event event) {} 
}

这些附加参数允许您方便地观察多个提供者和事件,而无需手动跟踪它们。

代码示例

代码示例来源:origin: k9mail/k-9

public OpenPgpApiManager(Context context, LifecycleOwner lifecycleOwner) {
  this.context = context;
  lifecycleOwner.getLifecycle().addObserver(this);
}

代码示例来源:origin: JessYanCoding/MVPArms

@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
  void onDestroy(LifecycleOwner owner) {
    owner.getLifecycle().removeObserver(this);
  }
}

代码示例来源:origin: JeremyLiao/LiveEventBus

@MainThread
public void observeSticky(@NonNull LifecycleOwner owner, @NonNull Observer<T> observer) {
  if (owner.getLifecycle().getCurrentState() == DESTROYED) {
    // ignore
    return;
  }
  LifecycleBoundObserver wrapper = new LifecycleBoundObserver(owner, observer);
  ObserverWrapper existing = mObservers.putIfAbsent(observer, wrapper);
  if (existing != null && !existing.isAttachedTo(owner)) {
    throw new IllegalArgumentException("Cannot add the same observer"
        + " with different lifecycles");
  }
  if (existing != null) {
    return;
  }
  owner.getLifecycle().addObserver(wrapper);
}

代码示例来源:origin: yangchaojiang/AaComponents

/**
 * 返回是否当前生命中周期状态
 *
 * @param state Lifecycle.State
 * @return boolean
 **/
public boolean isAtLeast(Lifecycle.State state) {
  return lifecycle.getCurrentState().isAtLeast(state);
}

代码示例来源:origin: WaylonBrown/LifecycleAwareRx

@OnLifecycleEvent(Lifecycle.Event.ON_ANY)
  void onStateChange() {
    if (lifecycleOwner != null && lifecycleOwner.getLifecycle().getCurrentState() == Lifecycle.State.DESTROYED) {
      // No memory leaks please
      lifecycleOwner.getLifecycle().removeObserver(this);
      lifecycleOwner = null;
    }
  }
}

代码示例来源:origin: JeremyLiao/LiveDataBus

@Override
public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<T> observer) {
  if (owner.getLifecycle().getCurrentState() == DESTROYED) {
    // ignore
    return;
  }
  try {
    //use ExternalLifecycleBoundObserver instead of LifecycleBoundObserver
    LifecycleBoundObserver wrapper = new ExternalLifecycleBoundObserver(owner, observer);
    wrapper.mLastVersion = getVersion();
    //Replace "ObserverWrapper existing = mObservers.putIfAbsent(observer, wrapper);"
    Object existing = callMethodPutIfAbsent(observer, wrapper);
    //Replace "if (existing != null && !existing.isAttachedTo(owner)) {"
    if (existing != null && !callMethodIsAttachedTo(existing, owner)) {
      throw new IllegalArgumentException("Cannot add the same observer"
          + " with different lifecycles");
    }
    if (existing != null) {
      return;
    }
    owner.getLifecycle().addObserver(wrapper);
  } catch (Exception e) {
    e.printStackTrace();
  }
}

代码示例来源:origin: WaylonBrown/LifecycleAwareRx

@Override
public boolean test(final T object) throws Exception {
  // We've already removed the reference, don't emit anymore items.
  if (lifecycleOwner == null) {
    return false;
  }
  
  boolean isDestroyed = lifecycleOwner.getLifecycle().getCurrentState() == Lifecycle.State.DESTROYED;
  if (isDestroyed) {
    // This should have been handled in handleLifecycleEvent() at this point, but just being safe to not have
    // memory leaks.
    lifecycleOwner = null;
  }
  // If not destroyed, predicate is true and emits streams items as normal. Otherwise it ends.
  return !isDestroyed;
}

代码示例来源:origin: listenzz/AndroidNavigation

@OnLifecycleEvent(Lifecycle.Event.ON_ANY)
void onStateChange() {
  if (getLifecycle().getCurrentState() == Lifecycle.State.DESTROYED) {
    tasks.clear();
    getLifecycle().removeObserver(this);
  } else {
    considerExecute();
  }
}

代码示例来源:origin: JessYanCoding/MVPArms

@Override
public void onStart() {
  //将 LifecycleObserver 注册给 LifecycleOwner 后 @OnLifecycleEvent 才可以正常使用
  if (mRootView != null && mRootView instanceof LifecycleOwner) {
    ((LifecycleOwner) mRootView).getLifecycle().addObserver(this);
    if (mModel!= null && mModel instanceof LifecycleObserver){
      ((LifecycleOwner) mRootView).getLifecycle().addObserver((LifecycleObserver) mModel);
    }
  }
  if (useEventBus())//如果要使用 EventBus 请将此方法返回 true
    EventBusManager.getInstance().register(this);//注册 EventBus
}

代码示例来源:origin: xcesco/kripton

if (owner.getLifecycle().getCurrentState() == DESTROYED) {
  return;
owner.getLifecycle().addObserver(wrapper);

代码示例来源:origin: WaylonBrown/LifecycleAwareRx

/**
   * A {@link LifecycleOwner} is considered active if it is either STARTED or RESUMED.
   * 
   * @param lifecycleOwner to check the state of.
   * @return whether the lifecycleOwner is active.
   */
  public static boolean isInActiveState(@Nullable LifecycleOwner lifecycleOwner) {
    return lifecycleOwner != null
      && lifecycleOwner.getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.STARTED);
  }
}

代码示例来源:origin: WaylonBrown/LifecycleAwareRx

/**
 * Decides whether the stream needs to be destroyed or subscribed to.
 */
private void handleCurrentLifecycleState() {
  if (lifecycleOwner != null &&
    lifecycleOwner.getLifecycle().getCurrentState() == Lifecycle.State.DESTROYED) {
    // No memory leaks please
    this.lifecycleOwner.getLifecycle().removeObserver(this);
    this.lifecycleOwner = null;
    this.baseReactiveType = null;
  } else if (LifecycleUtil.isInActiveState(lifecycleOwner) 
    && !subscribed 
    && baseReactiveType != null) {
    
    // Subscribe to stream with observer since the LifecycleOwner is now active but wasn't previously
    baseReactiveType.subscribeWithObserver();
    subscribed = true;
  }
}

代码示例来源:origin: JessYanCoding/MVPArms

/**
 * 只有当 {@code mRootView} 不为 null, 并且 {@code mRootView} 实现了 {@link LifecycleOwner} 时, 此方法才会被调用
 * 所以当您想在 {@link Service} 以及一些自定义 {@link View} 或自定义类中使用 {@code Presenter} 时
 * 您也将不能继续使用 {@link OnLifecycleEvent} 绑定生命周期
 *
 * @param owner link {@link SupportActivity} and {@link Fragment}
 */
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
void onDestroy(LifecycleOwner owner) {
  /**
   * 注意, 如果在这里调用了 {@link #onDestroy()} 方法, 会出现某些地方引用 {@code mModel} 或 {@code mRootView} 为 null 的情况
   * 比如在 {@link RxLifecycle} 终止 {@link Observable} 时, 在 {@link io.reactivex.Observable#doFinally(Action)} 中却引用了 {@code mRootView} 做一些释放资源的操作, 此时会空指针
   * 或者如果你声明了多个 @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) 时在其他 @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
   * 中引用了 {@code mModel} 或 {@code mRootView} 也可能会出现此情况
   */
  owner.getLifecycle().removeObserver(this);
}

代码示例来源:origin: yanzhenjie/NoHttp

private BaseView(Source source, Presenter presenter) {
  this.mSource = source;
  this.mPresenter = presenter;
  this.mSource.bind(this);
  invalidateOptionsMenu();
  mSource.setMenuClickListener(new Source.MenuClickListener() {
    @Override
    public void onHomeClick() {
      getPresenter().bye();
    }
    @Override
    public void onMenuClick(MenuItem item) {
      optionsItemSelected(item);
    }
  });
  getPresenter().getLifecycle().addObserver(new GenericLifecycleObserver() {
    @Override
    public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
      if (event == Lifecycle.Event.ON_RESUME) {
        resume();
      } else if (event == Lifecycle.Event.ON_PAUSE) {
        pause();
      } else if (event == Lifecycle.Event.ON_STOP) {
        stop();
      } else if (event == Lifecycle.Event.ON_DESTROY) {
        destroy();
      }
    }
  });
}

代码示例来源:origin: JeremyLiao/LiveEventBus

if (owner.getLifecycle().getCurrentState() == DESTROYED) {
  return;
owner.getLifecycle().addObserver(wrapper);

代码示例来源:origin: listenzz/AndroidNavigation

boolean isAtLeastStarted() {
  return getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED);
}

代码示例来源:origin: SilenceDut/TaskScheduler

@Override
  public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
    if(event == targetEvent) {
      if(mLifecycleOwner!=null ) {
        mLifecycleOwner.getLifecycle().removeObserver(this);
      }
      handler.removeCallbacks(LifecycleRunnableDelegate.this);
    }
  }
};

代码示例来源:origin: XunMengWinter/Now

@Override
public void onSubscribe(Disposable d) {
  mDisposable = d;
  if (mLifecycle != null)
    mLifecycle.addObserver(this);
}

代码示例来源:origin: listenzz/AndroidNavigation

public void scheduleTaskAtStarted(Runnable runnable) {
  if (getLifecycle().getCurrentState() != Lifecycle.State.DESTROYED) {
    assertMainThread();
    tasks.add(runnable);
    considerExecute();
  }
}

代码示例来源:origin: SilenceDut/TaskScheduler

@Override
  public void run() {
    if(mOriginRunnable!=null && mLifecycleOwner!=null) {
      mOriginRunnable.run();
      mLifecycleOwner.getLifecycle().removeObserver(mLifecycleObserver);
    }

  }
}

相关文章

微信公众号

最新文章

更多