我正在编写一个 Android 代码段来帮助跟踪 Android 事件作为应用程序开发人员的服务工具。
例如,主应用程序主体可以只是显示“hello world”。我的代码会监听应用程序事件,例如onStart()
、onResume()
、onDestroy()
等,并跟踪这些事件。
当然,代码可以直接插入主活动下。但这意味着我的代码将无处不在。有没有办法,我可以创建一个对象(即监听器),并且只要求应用程序开发人员添加 1~2 行来使用我的代码?
For API Level 14 and higher, you can call registerActivityLifecycleCallbacks()
on the Application
to set up a listener to be informed about activity lifecycle events.
试试这个方法
public class mYApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
registerActivityLifecycleCallbacks(new 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
静态方法来检查应用程序是在前台还是后台