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 File: ActivityView.java    From FairEmail with 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 File: AndroidLifecycleActivityTest.java    From RxLifecycle with 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 #3
Source File: BoundLocationManager.java    From android-lifecycles with 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 #4
Source File: DerivedFromJar_LifecycleAdapter.java    From android_9.0.0_r45 with 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 #5
Source File: ActivityBilling.java    From FairEmail with 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 #6
Source File: DynamicPresetsView.java    From dynamic-support with 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 #7
Source File: RecyclerViewAdapter.java    From ExoPlayer-Wrapper with 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 #8
Source File: Selection.java    From SAI with 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 #9
Source File: FragmentBase.java    From FairEmail with 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 #10
Source File: FragmentIdentity.java    From FairEmail with 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 #11
Source File: NoPackageTest.java    From android_9.0.0_r45 with 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 #12
Source File: ActivityView.java    From FairEmail with 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 #13
Source File: MobiusLoopViewModelTest.java    From mobius with 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 #14
Source File: BlockUnblockDialog.java    From mollyim-android with 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 #15
Source File: VoiceActivity.java    From voice-quickstart-android with MIT License 5 votes vote down vote up
private boolean isAppVisible() {
    return ProcessLifecycleOwner
            .get()
            .getLifecycle()
            .getCurrentState()
            .isAtLeast(Lifecycle.State.STARTED);
}
 
Example #16
Source File: ActivityView.java    From FairEmail with 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 #17
Source File: MobiusLoopViewModelTest.java    From mobius with 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 #18
Source File: MutableLiveQueueTest.java    From mobius with 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 #19
Source File: DifferentPackagesBase2_LifecycleAdapter.java    From android_9.0.0_r45 with 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 #20
Source File: MutableLiveQueueTest.java    From mobius with 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 #21
Source File: FragmentHelper.java    From AndroidNavigation with 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 #22
Source File: PowerMenuUtils.java    From PowerMenu with 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 #23
Source File: ObserverNoAdapter_LifecycleAdapter.java    From android_9.0.0_r45 with 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 #24
Source File: ActivityView.java    From FairEmail with 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();
}
 
Example #25
Source File: RecyclerViewAdapter.java    From ExoPlayer-Wrapper with Apache License 2.0 5 votes vote down vote up
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
protected void onPause() {
    MyLog.i("onActivityPause");
    for (ExoPlayerHelper exoPlayerHelper : getAllExoPlayers()) {
        exoPlayerHelper.onActivityPause();
    }
}
 
Example #26
Source File: FragmentAccount.java    From FairEmail with 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) {
                    final boolean save = (btnSave.getVisibility() == View.VISIBLE);
                    new Handler().post(new Runnable() {
                        @Override
                        public void run() {
                            scroll.smoothScrollTo(0, (save ? btnSave : btnCheck).getBottom());
                        }
                    });
                    if (save)
                        onSave(false);
                    else
                        onCheck();
                } else if (getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.STARTED))
                    getParentFragmentManager().popBackStack();
                break;
            case REQUEST_DELETE:
                if (resultCode == RESULT_OK)
                    onDelete();
                break;
        }
    } catch (Throwable ex) {
        Log.e(ex);
    }
}
 
Example #27
Source File: TabBarFragment.java    From AndroidNavigation with MIT License 5 votes vote down vote up
private void setSelectedIndexInternal(int index) {
    if (tabBarProvider != null) {
        tabBarProvider.setSelectedIndex(index);
    }

    if (selectedIndex == index) {
        return;
    }

    selectedIndex = index;
    FragmentManager fragmentManager = getChildFragmentManager();
    AwesomeFragment previous = (AwesomeFragment) fragmentManager.getPrimaryNavigationFragment();
    AwesomeFragment current = fragments.get(index);
    FragmentTransaction transaction = fragmentManager.beginTransaction();
    transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
    transaction.setPrimaryNavigationFragment(current);
    if (previous != null && previous.isAdded()) {
        setPresentAnimation(current, previous);
        transaction.setMaxLifecycle(previous, Lifecycle.State.STARTED);
        transaction.hide(previous);
    }
    transaction.setMaxLifecycle(current, Lifecycle.State.RESUMED);
    transaction.show(current);
    transaction.commit();
    FragmentHelper.executePendingTransactionsSafe(fragmentManager);

    if (tabBar != null) {
        NavigationFragment navigationFragment = current.getNavigationFragment();
        if (navigationFragment != null && navigationFragment.shouldHideTabBarWhenPushed()) {
            if (navigationFragment.getChildFragmentCountAtBackStack() <= 1) {
                showTabBar();
            } else {
                hideTabBar();
            }
        } else {
            showTabBar();
        }
    }
}
 
Example #28
Source File: ActivitySetup.java    From FairEmail with GNU General Public License v3.0 5 votes vote down vote up
private void onMenuOrder(int title, Class clazz) {
    if (getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.STARTED))
        getSupportFragmentManager().popBackStack("order", FragmentManager.POP_BACK_STACK_INCLUSIVE);

    Bundle args = new Bundle();
    args.putInt("title", title);
    args.putString("class", clazz.getName());

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

    FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
    fragmentTransaction.replace(R.id.content_frame, fragment).addToBackStack("order");
    fragmentTransaction.commit();
}
 
Example #29
Source File: ActivitySetup.java    From FairEmail with 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();
}
 
Example #30
Source File: ActivityBase.java    From FairEmail with GNU General Public License v3.0 5 votes vote down vote up
void addKeyPressedListener(final IKeyPressedListener listener, LifecycleOwner owner) {
    Log.d("Adding back listener=" + listener);
    keyPressedListeners.add(listener);

    owner.getLifecycle().addObserver(new LifecycleObserver() {
        @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
        public void onDestroyed() {
            Log.d("Removing back listener=" + listener);
            keyPressedListeners.remove(listener);
        }
    });
}