Question

Please review following code, i am not understanding where i am WRONG. I need to know in Broadcastreciever whether APPLICATION IS AT FOREGROUND or in BACKGROUND. But in Recevier it always Returning FALSE. Why the value of static variable in BASEAPPLICATION lost?? Why its Showing FALSE always

public class Main extends Activity  {
        @Override
        protected void onResume() {
                  super.onResume();
                  BaseApplication.activityResumed();
                  AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
                  Intent intent = new Intent(context, Recevier.class);
                  PendingIntent pi = PendingIntent.getBroadcast(context, intentCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
                  am.set(AlarmManager.RTC_WAKEUP, System.currentMilliSeconds() + 2000, pi);
        }
        protected void onStop() {
            super.onStop();
            BaseApplication.activityPaused();
            }

BROADCAST RECIEVER

@Override
    public void onReceive(Context context, Intent intent) {
        if(BaseApplication.isActivityVisible()){
         // Application is Running

        }
       else{
          // Applicaiton is not Running
//**ALWAYS GIVING FALSE**
            }
    }

*BASE APPLICATION *

public class BaseApplication {
    public static boolean isActivityVisible() {

        return activityVisible;
      }  

      public static void activityResumed() {
        activityVisible = true;

      }

      public static void activityPaused() {
        activityVisible = false;

      }

      private static boolean activityVisible;

}
Was it helpful?

Solution

You had better to check the top activity of activity stack.

public boolean isActivityVisible(Context context) {
    ActivityManager am = (ActivityManager) context.
    getSystemService(Activity.ACTIVITY_SERVICE);
    String className = am.getRunningTasks(1).get(0).topActivity.getClassName();
    return Main.class.getName().equals(className);
}

OTHER TIPS

The problem is the application is not aware of your BaseApplication class.

You should:

  1. Your base application class should extend Application object

  2. Your manifest should point out in the application tag the attribute name and point to you application object

P.S. the BaseApplication.activityPaused(); should go into onPause and not onStop

If you want to keep the state of "activityVisible" you need save it in SharedPreferences.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top