androidx.lifecycle.Lifecycle Java Examples

The following examples show how to use androidx.lifecycle.Lifecycle. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: FairEmail   Author: M66B   File: ActivityView.java    License: GNU General Public License v3.0 6 votes vote down vote up
private void onViewMessages(Intent intent) {
    if (getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.STARTED)) {
        getSupportFragmentManager().popBackStack("messages", FragmentManager.POP_BACK_STACK_INCLUSIVE);
        if (content_pane != null)
            getSupportFragmentManager().popBackStack("unified", 0);
    }

    Bundle args = new Bundle();
    args.putString("type", intent.getStringExtra("type"));
    args.putLong("account", intent.getLongExtra("account", -1));
    args.putLong("folder", intent.getLongExtra("folder", -1));

    FragmentMessages fragment = new FragmentMessages();
    fragment.setArguments(args);

    FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
    fragmentTransaction.replace(R.id.content_frame, fragment).addToBackStack("messages");
    fragmentTransaction.commit();
}
 
Example #2
Source Project: arcusandroid   Author: arcus-smart-home   File: ArcusApplication.java    License: Apache License 2.0 6 votes vote down vote up
private void setupLifecycleListener() {
    ProcessLifecycleOwner
            .get()
            .getLifecycle()
            .addObserver(new LifecycleObserver() {
                @OnLifecycleEvent(Lifecycle.Event.ON_START)
                public void onForeground() {
                    NetworkConnectionMonitor.getInstance().startListening(ArcusApplication.this);

                    // Go back to 30-second timeout
                    useNormalTimeoutDelay();

                    logger.debug("Application is resumed, cancelling connection close.");
                    handler.removeCallbacks(closeCorneaRunnable);
                }

                @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
                public void onBackground() {
                    logger.debug("Application is backgrounded, posting delayed connection close.");
                    handler.postDelayed(closeCorneaRunnable, DELAY_BEFORE_CLOSE_MS);
                    NetworkConnectionMonitor.getInstance().stopListening(ArcusApplication.this);
                }
            });
}
 
Example #3
Source Project: dynamic-support   Author: pranavpandey   File: DynamicPresetsView.java    License: Apache License 2.0 6 votes vote down vote up
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
public void loadPresets() {
    if (isPackageExists()) {
        if (isPermissionGranted()) {
            setPresetsVisible(true);
        } else {
            mInfo.setSubtitle(getContext().getString(
                    R.string.ads_permissions_subtitle_single));
            setPresetsVisible(false);            }
    } else {
        mInfo.setSubtitle(getContext().getString(R.string.ads_theme_presets_desc));
        setPresetsVisible(false);
    }

    if (mLifecycleOwner != null && isPermissionGranted()) {
        LoaderManager.getInstance(mLifecycleOwner).initLoader(
                ADS_LOADER_PRESETS, null, mLoaderCallbacks).forceLoad();
    }
}
 
Example #4
Source Project: android-lifecycles   Author: googlecodelabs   File: BoundLocationManager.java    License: Apache License 2.0 6 votes vote down vote up
@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);
    }
}
 
Example #5
Source Project: RxLifecycle   Author: trello   File: AndroidLifecycleActivityTest.java    License: Apache License 2.0 6 votes vote down vote up
private void testLifecycle(ActivityController<? extends LifecycleOwner> controller) {
    LifecycleProvider<Lifecycle.Event> provider = AndroidLifecycle.createLifecycleProvider(controller.get());

    TestObserver<Lifecycle.Event> testObserver = provider.lifecycle().test();

    controller.create();
    controller.start();
    controller.resume();
    controller.pause();
    controller.stop();
    controller.destroy();

    testObserver.assertValues(
            Lifecycle.Event.ON_CREATE,
            Lifecycle.Event.ON_START,
            Lifecycle.Event.ON_RESUME,
            Lifecycle.Event.ON_PAUSE,
            Lifecycle.Event.ON_STOP,
            Lifecycle.Event.ON_DESTROY
    );
}
 
Example #6
Source Project: android_9.0.0_r45   Author: lulululbj   File: DerivedFromJar_LifecycleAdapter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void callMethods(LifecycleOwner owner, Lifecycle.Event event, boolean onAny,
        MethodCallsLogger logger) {
  boolean hasLogger = logger != null;
  if (onAny) {
    return;
  }
  if (event == Lifecycle.Event.ON_START) {
    if (!hasLogger || logger.approveCall("doOnStart", 1)) {
      mReceiver.doOnStart();
    }
    if (!hasLogger || logger.approveCall("doAnother", 1)) {
      mReceiver.doAnother();
    }
    return;
  }
  if (event == Lifecycle.Event.ON_PAUSE) {
    if (!hasLogger || logger.approveCall("doOnPause", 2)) {
      LibraryBaseObserver_LifecycleAdapter.__synthetic_doOnPause(mReceiver,owner);
    }
    return;
  }
}
 
Example #7
Source Project: FairEmail   Author: M66B   File: ActivityBilling.java    License: GNU General Public License v3.0 6 votes vote down vote up
void addBillingListener(final IBillingListener listener, LifecycleOwner owner) {
    Log.i("IAB adding billing listener=" + listener);
    listeners.add(listener);

    //if (billingClient != null)
    //    if (billingClient.isReady()) {
    //        listener.onConnected();
    //        queryPurchases();
    //    } else
    //        listener.onDisconnected();

    owner.getLifecycle().addObserver(new LifecycleObserver() {
        @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
        public void onDestroyed() {
            Log.i("IAB removing billing listener=" + listener);
            listeners.remove(listener);
        }
    });
}
 
Example #8
Source Project: mollyim-android   Author: mollyim   File: BlockUnblockDialog.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static void showBlockFor(@NonNull Context context,
                                @NonNull Lifecycle lifecycle,
                                @NonNull Recipient recipient,
                                @NonNull Runnable onBlock)
{
  SimpleTask.run(lifecycle,
                 () -> buildBlockFor(context, recipient, onBlock, null),
                 AlertDialog.Builder::show);
}
 
Example #9
Source Project: mollyim-android   Author: mollyim   File: BlockUnblockDialog.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static void showUnblockFor(@NonNull Context context,
                                  @NonNull Lifecycle lifecycle,
                                  @NonNull Recipient recipient,
                                  @NonNull Runnable onUnblock)
{
  SimpleTask.run(lifecycle,
                 () -> buildUnblockFor(context, recipient, onUnblock),
                 AlertDialog.Builder::show);
}
 
Example #10
Source Project: FairEmail   Author: M66B   File: ActivityView.java    License: GNU General Public License v3.0 5 votes vote down vote up
private void onMenuFolders(long account) {
    if (getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.STARTED))
        getSupportFragmentManager().popBackStack("unified", 0);

    Bundle args = new Bundle();
    args.putLong("account", account);

    FragmentFolders fragment = new FragmentFolders();
    fragment.setArguments(args);

    FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
    fragmentTransaction.replace(R.id.content_frame, fragment).addToBackStack("folders");
    fragmentTransaction.commit();
}
 
Example #11
Source Project: Lassi-Android   Author: Mindinventory   File: CameraView.java    License: MIT License 5 votes vote down vote up
/**
 * Destroys this instance, releasing immediately
 * the camera resource.
 */
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
public void destroy() {
    clearCameraListeners();
    clearFrameProcessors();
    mCameraController.destroy();
    if (mCameraPreview != null) mCameraPreview.onDestroy();
}
 
Example #12
Source Project: Hentoid   Author: avluis   File: HentoidApp.java    License: Apache License 2.0 5 votes vote down vote up
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
private void onMoveToBackground() {
    Timber.d("Moving to background");
    if (enabled && !Preferences.getAppLockPin().isEmpty() && Preferences.isLockOnAppRestore()) {
        HentoidApp.setUnlocked(false);
        HentoidApp.setLockInstant(Instant.now().toEpochMilli());
    }
}
 
Example #13
Source Project: ExoPlayer-Wrapper   Author: Pulimet   File: RecyclerViewAdapter.java    License: Apache License 2.0 5 votes vote down vote up
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
protected void onStop() {
    MyLog.i("onActivityStop");
    for (ExoPlayerHelper exoPlayerHelper : getAllExoPlayers()) {
        exoPlayerHelper.onActivityStop();
    }
}
 
Example #14
Source Project: FairEmail   Author: M66B   File: ActivityView.java    License: GNU General Public License v3.0 5 votes vote down vote up
private void onViewThread(Intent intent) {
    boolean found = intent.getBooleanExtra("found", false);

    if (!found && getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.STARTED))
        getSupportFragmentManager().popBackStack("thread", FragmentManager.POP_BACK_STACK_INCLUSIVE);

    Bundle args = new Bundle();
    args.putLong("account", intent.getLongExtra("account", -1));
    args.putLong("folder", intent.getLongExtra("folder", -1));
    args.putString("thread", intent.getStringExtra("thread"));
    args.putLong("id", intent.getLongExtra("id", -1));
    args.putBoolean("filter_archive", intent.getBooleanExtra("filter_archive", true));
    args.putBoolean("found", found);

    FragmentMessages fragment = new FragmentMessages();
    fragment.setArguments(args);

    int pane;
    if (content_pane == null)
        pane = R.id.content_frame;
    else {
        pane = R.id.content_pane;
        content_separator.setVisibility(View.VISIBLE);
        content_pane.setVisibility(View.VISIBLE);
        args.putBoolean("pane", true);
    }

    FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
    fragmentTransaction.replace(pane, fragment).addToBackStack("thread");
    fragmentTransaction.commit();
}
 
Example #15
Source Project: FairEmail   Author: M66B   File: ViewModelMessages.java    License: GNU General Public License v3.0 5 votes vote down vote up
void setCallback(LifecycleOwner owner, BoundaryCallbackMessages.IBoundaryCallbackMessages callback) {
    if (boundary != null) {
        boundary.setCallback(callback);

        owner.getLifecycle().addObserver(new LifecycleObserver() {
            @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
            public void onDestroyed() {
                boundary.destroy();
            }
        });
    }
}
 
Example #16
Source Project: ExoPlayer-Wrapper   Author: Pulimet   File: RecyclerViewAdapter.java    License: Apache License 2.0 5 votes vote down vote up
@OnLifecycleEvent(Lifecycle.Event.ON_START)
protected void onStart() {
    MyLog.i("onActivityStart");
    for (ExoPlayerHelper exoPlayerHelper : getAllExoPlayers()) {
        exoPlayerHelper.onActivityStart();
    }
}
 
Example #17
Source Project: SAI   Author: Aefyr   File: Selection.java    License: GNU General Public License v3.0 5 votes vote down vote up
public void observe(LifecycleOwner lifecycleOwner, Observer<Key> observer) {
    if (lifecycleOwner.getLifecycle().getCurrentState() == Lifecycle.State.DESTROYED)
        return;

    addObserver(observer);
    lifecycleOwner.getLifecycle().addObserver(new DefaultLifecycleObserver() {
        @Override
        public void onDestroy(@NonNull LifecycleOwner owner) {
            removeObserver(observer);
        }
    });
}
 
Example #18
Source Project: FairEmail   Author: M66B   File: FragmentBase.java    License: GNU General Public License v3.0 5 votes vote down vote up
protected void finish() {
    if (finished)
        return;
    finished = true;

    if (getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.STARTED))
        getParentFragmentManager().popBackStack();
    else
        finish = true;
}
 
Example #19
Source Project: FairEmail   Author: M66B   File: FragmentIdentity.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    try {
        switch (requestCode) {
            case REQUEST_COLOR:
                if (resultCode == RESULT_OK && data != null) {
                    if (ActivityBilling.isPro(getContext())) {
                        Bundle args = data.getBundleExtra("args");
                        btnColor.setColor(args.getInt("color"));
                    } else
                        startActivity(new Intent(getContext(), ActivityBilling.class));
                }
                break;
            case REQUEST_SAVE:
                if (resultCode == RESULT_OK) {
                    new Handler().post(new Runnable() {
                        @Override
                        public void run() {
                            scroll.smoothScrollTo(0, btnSave.getBottom());
                        }
                    });
                    onSave(false);
                } else if (getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.STARTED))
                    getParentFragmentManager().popBackStack();
                break;
            case REQUEST_DELETE:
                if (resultCode == RESULT_OK)
                    onDelete();
                break;
            case REQUEST_SIGNATURE:
                if (resultCode == RESULT_OK)
                    onHtml(data.getExtras());
                break;
        }
    } catch (Throwable ex) {
        Log.e(ex);
    }
}
 
Example #20
Source Project: android_9.0.0_r45   Author: lulululbj   File: NoPackageTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void init() {
    mLifecycleOwner = mock(LifecycleOwner.class);
    mLifecycle = mock(Lifecycle.class);
    when(mLifecycleOwner.getLifecycle()).thenReturn(mLifecycle);
    mRegistry = new LifecycleRegistry(mLifecycleOwner);
}
 
Example #21
Source Project: mobius   Author: spotify   File: MobiusLoopViewModelTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testViewModelDoesNotTryToForwardEventsIntoLoopAfterCleared() {
  fakeLifecycle.handleLifecycleEvent(Lifecycle.Event.ON_RESUME);
  underTest.onCleared();
  underTest.dispatchEvent(new TestEvent("don't record me"));
  assertThat(recordedEvents.size(), equalTo(0));
}
 
Example #22
Source Project: voice-quickstart-android   Author: twilio   File: VoiceActivity.java    License: MIT License 5 votes vote down vote up
private boolean isAppVisible() {
    return ProcessLifecycleOwner
            .get()
            .getLifecycle()
            .getCurrentState()
            .isAtLeast(Lifecycle.State.STARTED);
}
 
Example #23
Source Project: mobius   Author: spotify   File: MobiusLoopViewModelTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testViewModelSendsEffectsIntoLoop() {
  fakeLifecycle.handleLifecycleEvent(Lifecycle.Event.ON_RESUME);
  underTest.dispatchEvent(new TestEvent("testable"));
  assertThat(recordedEvents.size(), equalTo(1));
  assertThat(recordedEvents.get(0).name, equalTo("testable"));
}
 
Example #24
Source Project: mobius   Author: spotify   File: MutableLiveQueueTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldSendQueuedEffectsIfObserverSwappedToResumedOneClearing() {
  fakeLifecycleOwner1.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE);

  mutableLiveQueue.setObserver(fakeLifecycleOwner1, s -> {}, s -> {});
  mutableLiveQueue.post("one");
  mutableLiveQueue.post("two");
  fakeLifecycleOwner2.handleLifecycleEvent(Lifecycle.Event.ON_RESUME);
  mutableLiveQueue.setObserver(fakeLifecycleOwner2, liveObserver, pausedObserver);

  assertThat(liveObserver.valueCount(), equalTo(0));
  pausedObserver.assertValues(queueOf("one", "two"));
}
 
Example #25
Source Project: android_9.0.0_r45   Author: lulululbj   File: DifferentPackagesBase2_LifecycleAdapter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void callMethods(LifecycleOwner owner, Lifecycle.Event event, boolean onAny,
    MethodCallsLogger logger) {
  boolean hasLogger = logger != null;
  if (onAny) {
    return;
  }
  if (event == Lifecycle.Event.ON_STOP) {
    if (!hasLogger || logger.approveCall("onStop", 2)) {
      mReceiver.onStop(owner);
    }
    return;
  }
}
 
Example #26
Source Project: mobius   Author: spotify   File: MutableLiveQueueTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldSendLiveAndQueuedEventsWhenRunningAndThenPausedObserver() {
  fakeLifecycleOwner1.handleLifecycleEvent(Lifecycle.Event.ON_RESUME);

  mutableLiveQueue.setObserver(fakeLifecycleOwner1, liveObserver, pausedObserver);
  mutableLiveQueue.post("one");
  fakeLifecycleOwner1.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE);
  mutableLiveQueue.post("two");
  fakeLifecycleOwner1.handleLifecycleEvent(Lifecycle.Event.ON_RESUME);

  liveObserver.assertValues("one");
  pausedObserver.assertValues(queueOf("two"));
}
 
Example #27
Source Project: AndroidNavigation   Author: listenzz   File: FragmentHelper.java    License: MIT License 5 votes vote down vote up
public static void addFragmentToAddedList(@NonNull FragmentManager fragmentManager, int containerId, @NonNull AwesomeFragment fragment, @NonNull Lifecycle.State maxLifecycle, boolean primary) {
    if (fragmentManager.isDestroyed()) {
        return;
    }

    FragmentTransaction transaction = fragmentManager.beginTransaction();
    transaction.add(containerId, fragment, fragment.getSceneId());
    if (primary) {
        transaction.setPrimaryNavigationFragment(fragment); // primary
    }
    transaction.setMaxLifecycle(fragment, maxLifecycle);
    transaction.commit();
    executePendingTransactionsSafe(fragmentManager);
}
 
Example #28
Source Project: PowerMenu   Author: skydoves   File: PowerMenuUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static PowerMenu getHamburgerPowerMenu(
    Context context,
    LifecycleOwner lifecycleOwner,
    OnMenuItemClickListener<PowerMenuItem> onMenuItemClickListener,
    OnDismissedListener onDismissedListener) {
  return new PowerMenu.Builder(context)
      .addItem(new PowerMenuItem("Novel", true))
      .addItem(new PowerMenuItem("Poetry", false))
      .addItem(new PowerMenuItem("Art", false))
      .addItem(new PowerMenuItem("Journals", false))
      .addItem(new PowerMenuItem("Travel", false))
      .setAutoDismiss(true)
      .setLifecycleOwner(lifecycleOwner)
      .setAnimation(MenuAnimation.SHOWUP_TOP_LEFT)
      .setCircularEffect(CircularEffect.BODY)
      .setMenuRadius(10f)
      .setMenuShadow(10f)
      .setTextColor(ContextCompat.getColor(context, R.color.md_grey_800))
      .setTextSize(12)
      .setTextGravity(Gravity.CENTER)
      .setTextTypeface(Typeface.create("sans-serif-medium", Typeface.BOLD))
      .setSelectedTextColor(Color.WHITE)
      .setMenuColor(Color.WHITE)
      .setSelectedMenuColor(ContextCompat.getColor(context, R.color.colorPrimary))
      .setOnMenuItemClickListener(onMenuItemClickListener)
      .setOnDismissListener(onDismissedListener)
      .setPreferenceName("HamburgerPowerMenu")
      .setInitializeRule(Lifecycle.Event.ON_CREATE, 0)
      .build();
}
 
Example #29
Source Project: android_9.0.0_r45   Author: lulululbj   File: ObserverNoAdapter_LifecycleAdapter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void callMethods(LifecycleOwner owner, Lifecycle.Event event, boolean onAny,
        MethodCallsLogger logger) {
    boolean hasLogger = logger != null;
    if (onAny) {
        return;
    }
    if (event == Lifecycle.Event.ON_STOP) {
        if (!hasLogger || logger.approveCall("doOnStop", 1)) {
            mReceiver.doOnStop();
        }
        return;
    }
}
 
Example #30
Source Project: FairEmail   Author: M66B   File: ActivityView.java    License: GNU General Public License v3.0 5 votes vote down vote up
private void onMenuLegend() {
    if (getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.STARTED))
        getSupportFragmentManager().popBackStack("legend", FragmentManager.POP_BACK_STACK_INCLUSIVE);

    FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
    fragmentTransaction.replace(R.id.content_frame, new FragmentLegend()).addToBackStack("legend");
    fragmentTransaction.commit();
}