Sunday, March 02, 2014

Android Tip - Detecting if your App is in the Foreground

Very often, your application will continue to work in the background. When an event occurred (such as entering an iBeacon region),  you might need to inform the user about it. If the application is in the foreground, you can use the Toast class to display a message. If the application is in the background, then a more persistent form of notification is needed, such as using Notification messages. In either case, you need to programmatically check if the application is running in the foreground or background when the event occurred.

Declare the following method named isAppInForeground() in your activity:

    //---helper method to determine if the app is in the
    // foreground---
    public static boolean isAppInForeground(Context context) {
        List tasks =
            ((ActivityManager) context.getSystemService(
             Context.ACTIVITY_SERVICE))
             .getRunningTasks(1);
        if (tasks.isEmpty()) {
            return false;
        }
        return tasks
            .get(0)
            .topActivity
            .getPackageName()
            .equalsIgnoreCase(context.getPackageName());
    }

In order for the method to work, you need to add the GET_TASKS permission in your AndroidManifest.xml file:

    <uses-permission
        android:name="android.permission.GET_TASKS"/>

To check if your app is in the foreground, simply call the isAppInForeground() method:

        if (isAppInForeground(getApplicationContext())) {
            Toast.makeText(this, "App is in the foreground",
                Toast.LENGTH_LONG).show();
        } else {
            //---create notifications, etc---       
        }


If the apps is in the background, you might want to create a notifications, etc, to inform the user.

No comments: