10

Observer methods are not being called. I tested ViewPagerCycler as in old school ways and working perfect. Thanks for help.

public final class ViewPagerCycler implements LifecycleObserver {

    private static final int PERIOD = 3000;

    private Timer mTimer;
    private TimerTask mTask;
    private Activity mActivity;
    private ViewPager mPager;

    public ViewPagerCycler(Activity activity, ViewPager pager) {
        mActivity = activity;
        mPager = pager;
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) public void start() {
        int count = mPager
            .getAdapter()
            .getCount();

        mTimer = new Timer();
        mTask = new TimerTask() {
            @Override public void run() {
                mActivity.runOnUiThread(new TimerTask() {
                    @Override public void run() {
                        mPager.setCurrentItem((mPager.getCurrentItem() + 1) % count, true);
                    }
                });
            }
        };
        mTimer.schedule(mTask, PERIOD, PERIOD);
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) public void stop() {
        mTask.cancel();
        mTimer.cancel();
        mTimer.purge();
    }
}

Activity is just summarized. I didn't add findViewByIds.

public class SummariziedActivity extends Activity implements LifecycleOwner {
   private final LifecycleRegistry mRegistry = new LifecycleRegistry(this);

   @Override protected void onCreate(@Nullable Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);

       mRegistry.addObserver(new ViewPagerCycler(mPager));
   }
}

In the build.gradle:

compile "android.arch.lifecycle:runtime:1.0.0-alpha2"
compile "android.arch.lifecycle:extensions:1.0.0-alpha2"
annotationProcessor "android.arch.lifecycle:compiler:1.0.0-alpha2"
azizbekian
  • 60,783
  • 13
  • 169
  • 249
Emre Aktürk
  • 3,306
  • 2
  • 18
  • 30

5 Answers5

5

Seems like implementing LifecycleRegistryOwner is not enough.

I came across the same problem in 1.0.0-alpha1 and I actually needed to forward lifecycle events to the Lifecycle instance myself in order to make it work. This is because either the documentation does not conform to the implementation, or this is a bug in the library.

I only used onStart() and onStop() in my Observers, so I forwarded these lifecycle events to the Lifecycle.

abstract class LifecyclePreferenceFragment : PreferenceFragment(), LifecycleRegistryOwner {

    private val mLifecycleRegistry = LifecycleRegistry(this)

    override fun getLifecycle() = mLifecycleRegistry

    override fun onStart() {
        super.onStart()
        lifecycle.handleLifecycleEvent(Lifecycle.Event.ON_START)
    }

    override fun onStop() {
        super.onStop()
        lifecycle.handleLifecycleEvent(Lifecycle.Event.ON_STOP)
    }
}
Yaroslav Mytkalyk
  • 16,950
  • 10
  • 72
  • 99
4

Instead of extending ordinary Activity, you should extend from LifecycleActivity.

Otherwise, you can refer to "Implementing LifecycleOwner in custom activities and fragments":

Any custom fragment or activity can be turned into a LifecycleOwner by implementing the built-in LifecycleRegistryOwner interface (instead of extending LifecycleFragment or LifecycleActivity).


    public class MyFragment extends Fragment implements LifecycleRegistryOwner {
        LifecycleRegistry lifecycleRegistry = new LifecycleRegistry(this);

        @Override
        public LifecycleRegistry getLifecycle() {
            return lifecycleRegistry;
        }
    }

If you have a custom class that you would like to make a LifecycleOwner, you can use the LifecycleRegistry class, but you will need to forward events into that class. This forwarding is done automatically for fragments and activities if they implement the LifecycleRegistryOwner interface.

azizbekian
  • 60,783
  • 13
  • 169
  • 249
  • Actually i am using Custom Activity, Reference : Implementing LifecycleOwner in custom activities and fragments (https://developer.android.com/topic/libraries/architecture/lifecycle.html) – Emre Aktürk Jun 06 '17 at 08:03
  • Yes, but you haven't correctly applied suggestions specified [in docs](https://developer.android.com/topic/libraries/architecture/lifecycle.html#implementing-lco). – azizbekian Jun 06 '17 at 08:05
  • I agree here, @EmreAktürk you should implement `LifecycleRegistryOwner`, otherwise you have to forward lifecycle events by yourself to your observer. – romtsn Jun 06 '17 at 08:06
  • Oh didnt noticed that I just implemented wrong Interface. Therefore there was no exception. I will accept answer after testing in a hour. :) – Emre Aktürk Jun 06 '17 at 08:13
  • I exactly implement LifecycleOwner Actvity but any lifecycle events not triggers. – Mahdi Aug 28 '18 at 10:12
  • Dec 2018 it seems LifecycleRegistryOwner is deprecated. – Willa Dec 27 '18 at 00:41
3

The problem is that you are extending the platform default Activity class instead of the support library's FragmentActivity.

This is what a Google engineer states in this bug report:

Yeah, we don't currently target platform Activity / Fragments.

I'm keeping this open, but we are not looking to fix this in the nearest future.

PS for people who uses platform fragments: please consider the usage support library fragments. When you use platform fragments, it means that your code depends on multiple years old implementation of fragments, which is shipped with a device. Those implementation are usually very old and has a lot of bugs that are already fixed in support library.

You can see in the lifecycle implementation that the lifecycle tracking is only enabled for FragmentActivity, for instance in the following extract of LifecycleDispatcher.java:

    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
        if (activity instanceof FragmentActivity) {
            ((FragmentActivity) activity).getSupportFragmentManager()
                    .registerFragmentLifecycleCallbacks(mFragmentCallback, true);
        }
        ReportFragment.injectIfNeededIn(activity);
    }

    @Override
    public void onActivityStopped(Activity activity) {
        if (activity instanceof FragmentActivity) {
            markState((FragmentActivity) activity, CREATED);
        }
    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
        if (activity instanceof FragmentActivity) {
            markState((FragmentActivity) activity, CREATED);
        }
    }

For more info on how lifecycle events dispatch is implemented you can see this other answer of mine: https://stackoverflow.com/a/45701439/2510655

Samuel Peter
  • 4,136
  • 2
  • 34
  • 42
  • However, I'm using `AppCompatActivity` which extends `FragmentActivity`, and it still does not work. – rwst Apr 02 '22 at 15:30
3

Starting from Support Library 26.1.0, if your Activity/Fragment extends from its classes, you get the lifecycle callbacks for free.

This is why you can do something like that:

https://developer.android.com/topic/libraries/architecture/lifecycle#lc

lifecycle.addObserver(object : DefaultLifecycleObserver {
    override fun onDestroy(owner: LifecycleOwner) {
        Log.d("AppLog", "onDestroy")
    }
android developer
  • 114,585
  • 152
  • 739
  • 1,270
0

Lifecycle.Observer(new observer);

to

getLifecycle().Observer(new observer);

100% working

amra ram
  • 81
  • 1
  • 2