3

i want to check whether the my application is in a background or in a Foreground and i also want to check the app in open or not using BroadcastReceiver

public class CheckRunningApplicationReceiver extends BroadcastReceiver {
Context mContext;

public int mId = 1000;
NotificationManager mNotificationManager;

@Override
public void onReceive(Context aContext, Intent anIntent) {
    mContext = aContext;
    Boolean isAppOpen = isApplicationSentToBackground(aContext);
    mNotificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
    if (isAppOpen) {
        //openNotification();
    } else {
        //mNotificationManager.cancel(mId);
    }

}

private void openNotification() {// Instantiate notification with icon and
                                    // ticker message
    Notification notification = new Notification(R.drawable.ic_launcher,"Notification message!", System.currentTimeMillis());
    PendingIntent i = PendingIntent.getActivity(mContext, 0, new Intent(mContext,MainActivity.class), 0);
    notification.setLatestEventInfo(mContext, "Notification Created","Click here to see the message", i);
    notification.flags = Notification.FLAG_ONGOING_EVENT; 
    mNotificationManager.notify(mId, notification);
}

public static boolean isApplicationSentToBackground(final Context context) {
    ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    List<RunningTaskInfo> tasks = am.getRunningTasks(1);
    if (!tasks.isEmpty()) {
        ComponentName topActivity = tasks.get(0).topActivity;
        if (!topActivity.getPackageName().equals(context.getPackageName())) {
            return true;
        }
    }

    return false;
}

}

is there any solution for this, help me , Thanks.

Gaurav Mandlik
  • 525
  • 1
  • 9
  • 42
  • I don't know if this works but you can try this http://stackoverflow.com/questions/3667022/checking-if-an-android-application-is-running-in-the-background/5862048#5862048 – Sunil Sunny Apr 28 '16 at 07:33
  • I've had great success with the code from Steve Liles at this blog post: [Is my Android app currently foreground or background?](http://steveliles.github.io/is_my_android_app_currently_foreground_or_background.html) – Richard Le Mesurier Apr 28 '16 at 08:22

2 Answers2

0

A BroadcastReceiver works even when the app is in the background because the event that the receiver picks up are sent globally, and each app is registered to listen in on these, regardless of whether or not app is running.

To deal with this, in your BroadcastReceiver's onReceive code, check if your app is in the foreground.

There is one--and only one that I know of--consistently effective method to do this. You need to keep track of your pause/resume actions for your application. Ensure that you check this in every activity.

There is some sample code in this answer . In your case, you would want to check MyApplication.isActivityVisible() == true as a validation before doing anything from your BroadcastReceiver.

Community
  • 1
  • 1
Nowshad
  • 294
  • 1
  • 14
-1

In your activity register broadcast receiver to check activity is in foreground or background.

StackAnswer.java
public class StackAnswer extends Activity {
    public static final int IS_ALIVE = Activity.RESULT_FIRST_USER;
    public static final String CHECK_ALIVE_ACTION = "CHECK_ALIVE_ACTION";
    private BroadcastReceiver mRefreshReceiver;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mRefreshReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {

                Log.i("onReceive","BroadcastIntent received in MainActivity");

                // TODO:                
                // Check to make sure this is an ordered broadcast
                // Let sender know that the Intent was received
                // by setting result code to MainActivity.IS_ALIVE
                setResultCode(MainActivity.IS_ALIVE);
            }
        };
    }



    // Register the BroadcastReceiver
    @Override
    protected void onResume() {
        super.onResume();

        // TODO:
        // Register the BroadcastReceiver to receive a 
        // DATA_REFRESHED_ACTION broadcast
        IntentFilter filter = new IntentFilter();
        filter.addAction(CHECK_ALIVE_ACTION);         
        registerReceiver(mRefreshReceiver, filter);     

    }

    @Override
    protected void onPause() {

        // TODO:
        // Unregister the BroadcastReceiver if it has been registered
        // Note: To work around a Robotium issue - check that the BroadcastReceiver
        // is not null before you try to unregister it
        if(mRefreshReceiver!=null){
            unregisterReceiver(mRefreshReceiver);
        }
        super.onPause();
    }


}

Send broadcast from background to check weather activity is alive or not

   BackgroundTask.java
   public class BackgroundTask {

    private void checkIfForeground (Context mApplicationContext){
        mApplicationContext.sendOrderedBroadcast(new Intent(
                StackAnswer.CHECK_ALIVE_ACTION), null,
                new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                // TODO: Check whether the result code is not MainActivity.IS_ALIVE
                if (getResultCode() != StackAnswer.IS_ALIVE) {
                    //Background 
                }else{
                    //Foreground 
                }
            }
        }, null, 0, null, null);
    }
}
H4SN
  • 1,482
  • 3
  • 24
  • 43