2

I'm trying to display a notification (if you click on it, opens an Activity with Dialog) if App is closed or running on background, but if it is open or running on foreground I want to show the Dialog directly.

I have this code:

@Override
public void onReceive( Context context, Intent intent )
{
    if ( RunningHelper.isAppRunning(context, Constants.PROJECT_NAME ) )
    {
        Log.d("Running", "--------APP RUNNING");


    }
    else
    {

        Log.d("Running", "--------APP NOT RUNNING");
        showNotification();
    }
}

My RunningHelper:

 public static boolean isAppRunning(final Context context, final String packageName) {
    final ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    final List<ActivityManager.RunningAppProcessInfo> procInfos = activityManager.getRunningAppProcesses();
    if (procInfos != null)
    {
        for (final ActivityManager.RunningAppProcessInfo processInfo : procInfos) {
            if (processInfo.processName.equals(packageName)) {
                return true;
            }
        }
    }
    return false;
}

The problem is the App always detect that is running onReceive(), Have someone any clue for do it correctly? Thanks.

fesave
  • 181
  • 13
  • 1
    you can check your activity is in foreground or background by following [way](https://stackoverflow.com/a/18469643/5308778) – yashkal Dec 13 '17 at 09:47

1 Answers1

1

Implement custom Application class

    public class ProjectApplication extends Application {

  public static boolean isActivityVisible() {
    return activityVisible;
  }  

  public static void activityResumed() {
    activityVisible = true;
  }

  public static void activityPaused() {
    activityVisible = false;
  }

  private static boolean activityVisible;
}

Dont forget to make entry in AndroidManifest of your application class.

Add onPause and onResume to every Activity in the project or you can create a BaseActivity extending AppCompatActivity/FragmentActivity and all your project activity must extend BaseActivity

@Override

protected void onResume() {
  super.onResume();
  ProjectApplication.activityResumed();
}

@Override
protected void onPause() {
  super.onPause();
  ProjectApplication.activityPaused();
}

and when broadcast is received you can check if activity is in foreground or background

@Override
public void onReceive( Context context, Intent intent )
{
    if ( ProjectApplication.activityVisible)        {
     // application is in foreground and running
    // do stuff here
    }
    else
    {
        // application is in background
    // do stuff here

    }
}
yashkal
  • 713
  • 5
  • 20