使用ActivityLifecycleCallbacks自动记录Android生命周期事件?

时间:2012-05-15 18:07:16

标签: java android callback lifecycle

我正在尝试使用ActivityLifecycleCallbacks自动捕获和记录Android生命周期事件,但至少可以说这个问题的文档很少:

    public void registerActivityLifecycleCallbacks (Application.ActivityLifecycleCallbacks callback)

我不想扩展Activity类或覆盖现有的生命周期方法(onCreate,onResume等等)。我希望有一个单独的类来监听这些事件并采取相应的行动。

有没有人有这方面的经验,或者有关于如何运作的良好实体文档或教程的链接?具体来说,如何注册ActivityLifecycleCallbacks,以及如何处理它们?

4 个答案:

答案 0 :(得分:46)

我没有任何第一手经验但是从API判断你可以编写自己的类来实现Application.ActivityLifecycleCallbacks接口并在提供的Application类实例上注册该类

getApplicaton().registerActivityLifecycleCallbacks(yourCustomClass);

此课程将收到与您的个人活动相同的回调。祝你好运。

PS。这是API级别14 btw,因此它不适用于旧手机。

答案 1 :(得分:32)

我自己实现了Application.ActivityLifecycleCallbacks。我正在使用SherlockActivity,但正常的Activity类可能会有效。

首先,我正在创建一个界面,其中包含跟踪活动生命周期的所有方法:

public interface ActivityLifecycleCallbacks{
    public void onActivityStopped(Activity activity);
    public void onActivityStarted(Activity activity);
    public void onActivitySaveInstanceState(Activity activity, Bundle outState);
    public void onActivityResumed(Activity activity);
    public void onActivityPaused(Activity activity);
    public void onActivityDestroyed(Activity activity);
    public void onActivityCreated(Activity activity, Bundle savedInstanceState);
}

其次,我在我的应用程序类中实现了这个接口:

public class MyApplication extends Application implements my.package.ActivityLifecycleCallbacks{

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

    @Override
    public void onActivityStopped(Activity activity) {
        Log.i("Tracking Activity Stopped", activity.getLocalClassName());

    }

    @Override
    public void onActivityStarted(Activity activity) {
        Log.i("Tracking Activity Started", activity.getLocalClassName());

    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
        Log.i("Tracking Activity SaveInstanceState", activity.getLocalClassName());
    }

    @Override
    public void onActivityResumed(Activity activity) {
        Log.i("Tracking Activity Resumed", activity.getLocalClassName());
    }

    @Override
    public void onActivityPaused(Activity activity) {
        Log.i("Tracking Activity Paused", activity.getLocalClassName());
    }

    @Override
    public void onActivityDestroyed(Activity activity) {
        Log.i("Tracking Activity Destroyed", activity.getLocalClassName());
    }

    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
        Log.i("Tracking Activity Created", activity.getLocalClassName());
    }
}

第三,我正在创建一个从SherlockActivity扩展的类:

public class MySherlockActivity extends SherlockActivity {

    protected MyApplication nMyApplication;

    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        nMyApplication = (MyApplication) getApplication();
        nMyApplication.onActivityCreated(this, savedInstanceState);
    }

    protected void onResume() {
        // TODO Auto-generated method stub
        nMyApplication.onActivityResumed(this);
        super.onResume();

    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        nMyApplication.onActivityPaused(this);
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        nMyApplication.onActivityDestroyed(this);
        super.onDestroy();
    }

    @Override
    protected void onStart() {
        nMyApplication.onActivityStarted(this);
        super.onStart();
    }

    @Override
    protected void onStop() {
        nMyApplication.onActivityStopped(this);
        super.onStop();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        nMyApplication.onActivitySaveInstanceState(this, outState);
        super.onSaveInstanceState(outState);
    }   
}

第四,所有从SherlockActivity扩展的类,我替换为MySherlockActivity:

public class MainActivity extends MySherlockActivity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

}

现在,在logcat中,您将看到在MyApplication中进行的Interface实现中编写的日志。

<强>更新

此实现已经从API Level 9(Gingerbread),API Level 12(Honeycomb)和API Level 17(Jelly Bean)进行了测试,并且工作正常。可能适用于Android的旧版本。

答案 2 :(得分:3)

试试这个:http://engineering.meetme.com/2015/04/android-determine-when-app-is-opened-or-closed/#comment-202

它建议AppForegroundStateManager每个活动通过其onStop()onStart()函数进行报告,如下所示:

@Override
protected void onStart() {
    super.onStart();
    AppForegroundStateManager.getInstance().onActivityVisible(this);
}

@Override
protected void onStop() {
    AppForegroundStateManager.getInstance().onActivityNotVisible(this);
    super.onStop();
}

您的Application类实现了这样的侦听器:

public class MyApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        AppForegroundStateManager.getInstance().addListener(this);
    }

    @Override
    public void onAppForegroundStateChange(AppForegroundStateManager.AppForegroundState newState) {
        if (AppForegroundStateManager.AppForegroundState.IN_FOREGROUND.equals(newState)) {
            // App just entered the foreground. Do something here!
            Log.i(TAG, "App Just Entered the Foreground with launch mechanism of: " + mLaunchMechanism);
        } else {
            // App just entered the background. Set our launch mode back to the default of direct.
            mLaunchMechanism = LaunchMechanism.DIRECT;
        }
    }
}

它还包含用于确定应用程序打开方式的提示和技巧 - 来自通知,打开应用程序的URL或直接从应用程序菜单打开。这是通过Application类中的Enum完成的:

public enum LaunchMechanism {
    DIRECT,
    NOTIFICATION,
    URL,
    BACKGROUND
}

private LaunchMechanism mLaunchMechanism = LaunchMechanism.DIRECT;

public void setLaunchMechanism(LaunchMechanism launchMechanism) {
    mLaunchMechanism = launchMechanism;
}

在我们的实施中,我们有一些标志,用于指示我们何时开始启动第三方活动的活动,例如用户是否通过我们的应用程序拨打电话或是否启动了浏览器。在启动活动的onStop()中,我们会像这样进行检查,仅在这些标志为假时报告活动的不可见性:

if(!flag_userLaunchedThirdPartyActivity){
     AppForegroundStateManager.getInstance().onActivityNotVisible(this);
     }

用于检查应用程序是否进入后台 - 例如当设备屏幕变暗或用户接到电话时 - 它的工作方式如下:

public static boolean isApplicationGoingToBackground(final Context context) {

    ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    List<RunningTaskInfo> tasks = am.getRunningTasks(1);
    if (!tasks.isEmpty()) {
        ComponentName topActivity = tasks.get(0).topActivity;
        if (!topActivity.getPackageName().equals(context.getPackageName())) {
            setLaunchMechanism(LaunchMechanism.BACKGROUND);
            return true;
        }
    }

    setLaunchMechanism(LaunchMechanism.DIRECT);
    return false;
}

此解决方案不依赖于API级别,因此它应该一直工作回API级别。

答案 3 :(得分:1)

@Override
public void onCreate() {
    super.onCreate();
    registerActivityLifecycleCallbacks(MyApplication.this/*(Your Application Name)*/);

// registerActivityLifecycleCallbacks(MyApplication.this / (您的应用程序名称) / //只在Application类上添加这一行一切正常

}