How to get the foreground app and/or activity?

ilker Aktuna :

I am working on a remote control for integration between Android TV devices and Smartthings Hub. I want to be able to see which app is active (foreground, displayed to the user).

My app is a soft Keyboard and thus it is running as a service (Input Method Service)

I found the following code and tried it:

ActivityManager.RunningAppProcessInfo result=null;
String pname="process: ";
ActivityManager activityManager = (ActivityManager) ctx.getSystemService( Context.ACTIVITY_SERVICE );
List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();

Iterator <ActivityManager.RunningAppProcessInfo> i = appProcesses.iterator();

while(i.hasNext()){
    ActivityManager.RunningAppProcessInfo info = i.next();
    Log.d("LOG : " , info.processName);

    if(info.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND)
    {
         result=info;
         break;
    }
}

But it doesn't displa any apps. If I remove the condition

"info.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND"

then it displays my app (keyboard) as the running app.

So it seems like this only shows apps or activities that are part of my app. How can I reach this information for the whole Android system ? Does it require a permission ?

If this is not doable with a normal app, and is possible only with some additional permissions, or accessibility features, I am open to use it, because the app is not a commercial app and will not be distributed if any other Smartthings user doesn't ask for it. I just can't use rooted device. Other than that I can try anything.

ilker Aktuna :

This seems not possible, because Google has limited this feature to system apps only. There are many misleading answers about the problem. Unfortunately, most of the answers assume that we only want to check if our app is in foreground. But as described in the question, the problem is trying to get the active app (not our app) name.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=156500&siteId=1
Recommended