我正在撰写Android代码段,以帮助跟踪Android事件作为应用开发者的服务工具。
例如,主app界面可以只显示'hello world'。我的代码会收听应用事件,例如onStart()
,onResume()
,onDestroy()
等,并对这些事件进行跟踪。
当然,代码可以直接插入主活动下。但这意味着我的代码将遍布各个地方。有没有办法,我可以创建一个对象(即一个监听器),并且只请求app开发人员添加1~2个衬里来使用我的代码?
答案 0 :(得分:19)
对于API级别14及更高级别,您可以call registerActivityLifecycleCallbacks()
on the Application
设置一个侦听器,以了解有关活动生命周期事件的信息。
答案 1 :(得分:3)
尝试此方法
public class mYApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
registerActivityLifecycleCallbacks(new MyLifecycleHandler());
}
}
MyLifecycleHandler:
public class MyLifecycleHandler implements Application.ActivityLifecycleCallbacks {
private static int resumed;
private static int paused;
private static int started;
private static int stopped;
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
}
@Override
public void onActivityDestroyed(Activity activity) {
}
@Override
public void onActivityResumed(Activity activity) {
++resumed;
}
@Override
public void onActivityPaused(Activity activity) {
++paused;
android.util.Log.w("test", "application is in foreground: " + (resumed > paused));
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
@Override
public void onActivityStarted(Activity activity) {
++started;
}
@Override
public void onActivityStopped(Activity activity) {
++stopped;
android.util.Log.w("test", "application is visible: " + (started > stopped));
}
public static boolean isApplicationVisible() {
return started > stopped;
}
public static boolean isApplicationInForeground() {
return resumed > paused;
}
}
然后调用isApplicationInForeground
静态方法来检查应用程序是在前台还是后台