我正在开发一个Android应用程序,尝试注册活动生命周期回调。
在我的启动器活动(Agreement.java)的onCreate
方法中,我有以下内容:
this.getApplication().registerActivityLifecycleCallbacks(new LoginManager());
这个活动会检查是否已经同意了协议,如果是,则立即完成并调用LoginActivity.java,但是我在我的活动回调类中的toast通知和logcat消息都没有显示,因此看起来它似乎没有被触发。
下面是实现活动回调的LoginManager类:
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();
}
}
为了再次强调,Agreement类注册了生命周期回调(LoginManager),立即关闭并显示LoginActivity,但toast和logcat未触发。