@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) public void onPause() { final Fragment fragment = fragmentManager.findFragmentByTag(tag); if (fragment == null) { Log.w(TAG, "Could not find the fragment for preserving instance states."); return; } try { final String packageName = target.getClass().getPackage().getName(); final String className = getObjectClassName(target.getClass()); final Class<?> clazz = Class.forName(packageName + "." + className); final Object<T> object = (Object<T>) clazz.newInstance(); object.save(target); ((RetainFragment<T>) fragment).setObject(object); } catch (Exception e) { Log.w(TAG, "Failed to create a object instance for preserving instance states."); } }
private MethodSpec defineLifecycleHook() { final String methodName = "onLifecycleEvent"; Lifecycle.Event lifecycleEvent = annotatedElement.getAnnotation(LifecycleAware.class).value(); AnnotationSpec archLifeCycleSpec = AnnotationSpec.builder(OnLifecycleEvent.class) .addMember(ANNOT_DEFAULT_NAME, "$T.$L", Lifecycle.Event.class, lifecycleEvent) .build(); return MethodSpec.methodBuilder(lifecycleEvent.name()) .addAnnotation(archLifeCycleSpec) .addModifiers(Modifier.PUBLIC) .addStatement("$L.$L($T.$L)", FIELD_OBSERVER, methodName, Lifecycle.Event.class, lifecycleEvent) .build(); }
/** * Required to place inside your activities {@code onStart} method. You'll also most likely want * to check that this Location Layer plugin instance inside your activity is null or not. * * @since 0.1.0 */ @RequiresPermission(anyOf = {ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION}) @OnLifecycleEvent(Lifecycle.Event.ON_START) public void onStart() { if (locationLayerMode != LocationLayerMode.NONE) { setLocationLayerEnabled(locationLayerMode); } if (!compassManager.getCompassListeners().isEmpty() || (locationLayerMode == LocationLayerMode.COMPASS && compassManager.isSensorAvailable())) { compassManager.onStart(); } if (mapboxMap != null) { mapboxMap.addOnCameraMoveListener(this); } }
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME) void addLocationListener() { // Note: Use the Fused Location Provider from Google Play Services instead. // https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderApi mLocationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE); mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mListener); Log.d("BoundLocationMgr", "Listener added"); // Force an update with the last location, if available. Location lastLocation = mLocationManager.getLastKnownLocation( LocationManager.GPS_PROVIDER); if (lastLocation != null) { mListener.onLocationChanged(lastLocation); } }
/** * Like {@link #trackEvent(Event, Context, Bundle)}, but also starts a performance Trace. * * @param event {@link #trackEvent(Event, Context, Bundle)} * @param context {@link #trackEvent(Event, Context, Bundle)} * @param bundle {@link #trackEvent(Event, Context, Bundle)} * @param container lifecycle to attach Trace to (onDestroy will stop the trace). */ public static void trackEventStart(@NonNull final Event event, @NonNull final Context context, @Nullable final Bundle bundle, @Nullable final LifecycleOwner container) { trackEvent(event, context, bundle); if (sRunningEvents.containsKey(event)) { LOGGER.error("Event {} triggered while performance counting for it was already in " + "progress! Finishing now", event, new Throwable()); trackEventFinish(event); } Trace t = FirebasePerformance.startTrace(event.track()); sRunningEvents.put(event, t); t.start(); if (container != null) { // Container can be null if we test cross-activity lifecycle container.getLifecycle().addObserver(new LifecycleObserver() { @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) public void stopTrace() { trackEventFinish(event); } }); } }
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE) public void downloadFont() { Log.d(Tags.viewmodel.name(), "downloadFont: Running"); String query = "name=Open Sans&weight=800&italic=0"; FontRequest fontRequest = new FontRequest( "com.google.android.gms.fonts", "com.google.android.gms", query, R.array.com_google_android_gms_fonts_certs); FontsContractCompat.FontRequestCallback fontCallback = new FontsContractCompat.FontRequestCallback() { @Override public void onTypefaceRetrieved(Typeface typeface) { // If we got our font apply it to the toolbar styleToolbar(typeface); } @Override public void onTypefaceRequestFailed(int reason) { Log.w(Tags.viewmodel.name(), "Failed to fetch Toolbar font: " + reason); } }; // Start async fetch on the handler thread FontsContractCompat.requestFont( mContext, fontRequest, fontCallback, getFontHandlerThread()); }
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE) public void onCreate() { if (locationEngine.getValue() != null) { locationEngine.getValue().addLocationEngineListener(this); locationEngine.getValue().activate(); } }
@OnLifecycleEvent(Lifecycle.Event.ON_STOP) void stop() { if (alertDialog != null) { alertDialog.dismiss(); } }
/** * 只有当 {@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); }
@OnLifecycleEvent(value = Lifecycle.Event.ON_CREATE) protected void onCreate() { if (viewStateBundle.getBoolean(PROGRESS_BAR_STATE_KEY)) { if (isViewAttached()) getView().showProgress(); } }
@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; } }
/** * Required to place inside your activities {@code onStop} method. * * @since 0.1.0 */ @OnLifecycleEvent(Lifecycle.Event.ON_STOP) public void onStop() { stopAllAnimations(); if (compassManager != null && compassManager.isSensorAvailable()) { compassManager.onStop(); } if (locationEngine != null) { locationEngine.removeLocationEngineListener(this); } if (mapboxMap != null) { mapboxMap.removeOnCameraMoveListener(this); } }
/** * Creates a new scope for the given lifecycle owner (e.g. a Fragment or an Activity). * Note: The lifetime is * attached to the {@link android.arch.lifecycle.Lifecycle} AND the parent scope. So the returned * scope is destroyed if either of them is destroyed. */ public static Scope createScope(@Nullable Scope parent, LifecycleOwner lifecycleOwner) { Scope scope = new Scope(lifecycleOwner.toString(), parent); lifecycleOwner.getLifecycle().addObserver(new LifecycleObserver() { @OnLifecycleEvent(Event.ON_DESTROY) void onDestroy() { scope.destroy(); } }); if (lifecycleOwner instanceof Context) { scope.put(Android.NAME_CONTEXT, lifecycleOwner); } return scope; }
@OnLifecycleEvent(Lifecycle.Event.ON_ANY) void onEvent(LifecycleOwner owner, Lifecycle.Event event) { lifecycleSubject.onNext(event); if (event == Lifecycle.Event.ON_DESTROY) { owner.getLifecycle().removeObserver(this); } }
@OnLifecycleEvent(Lifecycle.Event.ON_START) void start() { if (!isRegistered) { IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); context.registerReceiver(internetConnectivityChangeBroadcastReceiver, intentFilter); isRegistered = true; } }
@OnLifecycleEvent(Lifecycle.Event.ON_STOP) void stop() { if (isRegistered) { context.unregisterReceiver(internetConnectivityChangeBroadcastReceiver); isRegistered = false; } }
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) void removeLocationListener() { if (mLocationManager == null) { return; } mLocationManager.removeUpdates(mListener); mLocationManager = null; Log.d("BoundLocationMgr", "Listener removed"); }
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE) @Override public void onStart() { if (useEventBus()) { //注册eventbus EventBus.getDefault().register(this); } }
@Override protected void onCreate(@Nullable final Bundle savedInstanceState) { super.onCreate(savedInstanceState); getLifecycle().addObserver(new LifecycleObserver() { @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) public void cleanDisposables() { getLifecycle().removeObserver(this); mDisposeOnDestroy.dispose(); } }); }
/** * Calls {@link WebView#destroy()} on the player. And unregisters the broadcast receiver (for network events), if registered. * Call this method before destroying the host Fragment/Activity, or register this View as an observer of its host lifcecycle */ @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) public void release() { youTubePlayer.destroy(); try { getContext().unregisterReceiver(networkReceiver); } catch (Exception ignore) { } }
@OnLifecycleEvent(Event.ON_ANY) void onStateChange(LifecycleOwner owner, Event event) { if (!isDisposed()) { if (!(event == ON_CREATE && eventsObservable.getValue() == event)) { // Due to the INITIALIZED->ON_CREATE mapping trick we do in backfill(), // we fire this conditionally to avoid duplicate CREATE events. eventsObservable.onNext(event); } observer.onNext(event); } }
@OnLifecycleEvent(Lifecycle.Event.ON_START) @MainThread public void onStart(){ uiReady = true; ((BaseTaskManager) getTaskManager()).setUIReady(uiReady); ((BaseTaskManager) getTaskManager()).attach(attachListener); }
@OnLifecycleEvent(Lifecycle.Event.ON_STOP) @MainThread public void onStop(){ uiReady = false; ((BaseTaskManager) getTaskManager()).setUIReady(uiReady); ((BaseTaskManager) getTaskManager()).detach(); }
/** * This method is optional to call and only clear a reference which is already set as "weak". * Calling this method might improve GC performance? */ @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) @MainThread public void onDestroy(){ // The TaskManager is retained so remove our reference to it, even though the // BaseTaskManager already holds this things as "weak" reference. ((BaseTaskManager) getTaskManager()).setInitialCallbackProvider(null); }
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE) protected void create() { IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(ACTION_NOTIFICATIONS_RETRIEVED); intentFilter.addAction(ACTION_ERROR_RETRIEVING_NOTIFICATIONS); mContext.registerReceiver(mNotificationsListener, intentFilter); // Request notifications from system Intent retrieveNotifications = new Intent(ACTION_RETRIEVE_NOTIFICATIONS); mContext.sendBroadcast(retrieveNotifications); }
@OnLifecycleEvent(Event.ON_STOP) protected void stop() { Log.e(TAG, "LocationListener STOP"); }
@SuppressWarnings("unused") @OnLifecycleEvent(Lifecycle.Event.ON_ANY) void onStateChange(final LifecycleOwner lifecycleOwner, final Lifecycle.Event event) { currentState = lifecycleOwner.getLifecycle().getCurrentState(); if (currentState == DESTROYED) { lock.writeLock().lock(); try { observers.remove(this); } finally { lock.writeLock().unlock(); } } }
@Override @OnLifecycleEvent(Lifecycle.Event.ON_START) public void startListening() { if (!mSnapshots.isListening(this)) { mSnapshots.addChangeEventListener(this); } }
/** * Start listening for database changes and populate the adapter. */ @OnLifecycleEvent(Lifecycle.Event.ON_START) public void startListening() { if (!mSnapshots.isListening(this)) { mSnapshots.addChangeEventListener(this); } }
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME) public abstract void connect();
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) public abstract void disconnect();
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) public abstract void destroy();
@OnLifecycleEvent(Lifecycle.Event.ON_START) public void onStart() { mapView.onStart(); }
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME) public void onResume() { mapView.onResume(); }
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) public void onPause() { mapView.onPause(); }
@OnLifecycleEvent(Lifecycle.Event.ON_STOP) public void onStop() { mapView.onStop(); }
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) public void onDestroy() { deactivateLocationEngine(); }