Search code examples
androidactivity-lifecycle

Registering Android activity lifecycle not being triggered


I am working on an Android app and I am trying to register the activity lifecycle call back.

In my launcher activity (Agreement.java) in the onCreate method I have the following:

this.getApplication().registerActivityLifecycleCallbacks(new LoginManager());

This activity does a check if the agreement has been agreed, and if so immediately finishes and calls LoginActivity.java but the toast notification I have in my activity call back class doesn't show and neither do my logcat messages so it doesn't look like its getting fired.

Below is the LoginManager class which implements the activity call backs

public class LoginManager extends Application implements Application.ActivityLifecycleCallbacks
{
    private final String TAG = "LoginManager";
    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState)
    {
        Toast.makeText(activity, "Activity Created", Toast.LENGTH_LONG).show();
        Log.d(TAG, "Activity Created");
        long currentEpochTime = System.currentTimeMillis() / 1000l;
        Log.d(TAG, "Current Epoch: " + currentEpochTime);
        CommonTasks commonTasks = new CommonTasks(activity);
        SharedPreferences settings = commonTasks.getAppsSharedPreferences();

        long timeDifference = currentEpochTime - settings.getLong(Defines.SharedPreferenceSettings.LAST_ACTIVE_EPOCH, 0);
        Log.d(TAG, "Time Difference: " + timeDifference);
        if (timeDifference >= 120) //2 Minutes
        {
            Log.d(TAG, "Logging out");
            //Over 2 minutes so we need to logout
            Intent intent = new Intent(activity, LoginActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            activity.startActivity(intent);
        }
        else
        {
            Log.d(TAG, "Not Logging Out");
            //No need to logout, save the current time
            SharedPreferences.Editor editor = settings.edit();
            editor.putLong(Defines.SharedPreferenceSettings.LAST_ACTIVE_EPOCH, currentEpochTime);
            editor.commit();
        }
    }

So just to reiterate, the agreement class registers the lifecycle callback (LoginManager) instantly closes and shows LoginActivity but the toast and logcat isn't triggered.


Solution

  • In your LoginManager class add

     @Override
        public void onCreate() {
            super.onCreate();
            registerActivityLifecycleCallbacks(this);
        }
    

    And remove

    this.getApplication().registerActivityLifecycleCallbacks(new LoginManager());
    

    from Agreement.java