I am writing an Android code segment to help tracing Android event as a service tool for app developers.
For example, the main app body can be just to display 'hello world'. My code will listen to the app event, such as onStart()
, onResume()
, onDestroy()
, etc, and keep a trace on these events.
Certainly, the code can be inserted directly under the main activity. But that means my code will be allover the places. Is there a way, I can create an object (i.e., a listener), and only request the app developer to add 1~2 liner to use my code?
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.
Try this Approach
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;
}
}
and then call isApplicationInForeground
static method to check if application is in foreground or background
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With