3

In my application i want to show a message using BroadcastReceiver, but i want it to display the toast message only when the application is not opened and currently running on the screen (it may be running in the background). But i am not finding the exact code to implement the condition accordingly.

I have tried the code,

    ActivityManager manager = 
        (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
    List<RunningAppProcessInfo> processes = manager.getRunningAppProcesses();

but it stop the message when running another application also.

Please help how i can make my code aware about whether the application currently opened or not? Thanks.

  • possible duplicate of [SendBroadcast if Activity or Notification](http://stackoverflow.com/questions/3865687/sendbroadcast-if-activity-or-notification) – CommonsWare Mar 13 '12 at 13:31
  • refer this http://stackoverflow.com/questions/6420767/monitor-currently-running-application – Aerrow Mar 13 '12 at 13:32

1 Answers1

-1

With credit to this answer, and, by extension, cyanogenmod 7.

You're halfway there. RunningAppProcessInfo has a field called pkgList, a String[] that contains all the package names in the process, which you can match against to determine if it's your app.

private RunningAppProcessInfo getForegroundApp() {
    RunningAppProcessInfo result=null, info=null;

    if(mActivityManager==null)
        mActivityManager = (ActivityManager)mContext.getSystemService(Context.ACTIVITY_SERVICE);
    List <RunningAppProcessInfo> l = mActivityManager.getRunningAppProcesses();
    Iterator <RunningAppProcessInfo> i = l.iterator();
    while(i.hasNext()){
        info = i.next();
        if(info.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND
                && !isRunningService(info.processName)){
            result=info;
            break;
        }
    }
    return result;

}

Community
  • 1
  • 1
Fishbreath
  • 407
  • 2
  • 9