How to know in BroadcastReceiver if App is running on foreground?

pgarriga picture pgarriga · May 9, 2014 · Viewed 12.9k times · Source

I am working in application that needs make a synchronization every night. I use Alarm Manager that calls a BroadcastReceiver at the hour that I want. The problem is that I cant make a synchronization if the application is running in foreground to avoid losing data. So I need to know in Broadcast Receiver if the app is running in foreground to cancel this synchronization.

I tried solutions that I found in StackOverflow: Checking if an Android application is running in the background But this parameter is always false in BroadcastReceiver, but true in activites.

Can anyone tell me which is the problem? What am I doing bad?

Really thanks!

Answer

Biraj Zalavadia picture Biraj Zalavadia · May 9, 2014

Try this way hope this works for you

public class MyBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        if (isAppForground(context)) {
            // App is in Foreground
        } else {
            // App is in Background
        }
    }

    public boolean isAppForground(Context mContext) {

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

        return true;
    }

}

Add this permission

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