1

I need to have information of which application is currently on screen. For example I have pressed Facebook and Facebook is on screen, I have pressed the home button and I don't have anything on the screen. I have pressed Google Chrome to get information that Google Chrome is on the top of the screen. To be more precise to get the package name of the application. Saw some implementations but they are all giving me the same result.

public class MyService extends Service {

private static MyService sMyService;

private static String foregroundPackageName;

public IBinder onBind(Intent intent) {
    sMyService = this;
    ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
    List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
    Log.d("topActivity", "CURRENT Activity ::" + taskInfo.get(0).topActivity.getClassName());
    ComponentName componentInfo = taskInfo.get(0).topActivity;
    foregroundPackageName = componentInfo.getPackageName();
    System.out.println("THIS IS THE FOREGROUND 
    ::::::::::::::::"+foregroundPackageName);
    return null;
}

public static String getForegroundPackageName() {
    return foregroundPackageName;
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}
}

This was just a test to see if I will get the on screen activity but all the time is printing only:

com.sec.android.app.launcher.activities.LauncherActivity.

Nicholas Nur
  • 228
  • 2
  • 12
f.trajkovski
  • 794
  • 9
  • 24
  • 1
    this will help you as getRunningTask() is deprecated now https://stackoverflow.com/questions/33918528/android-5-0-getrunningtasks-is-deprecated/33919161 – avez raj Dec 22 '17 at 13:25
  • "i have pressed the home button and I don't have anything on the screen" -- yes, you do. The home screen is "on the screen". Also, in a multi-window environment, there may be N apps that are "on the screen". There is no single "foreground package name", and on the whole, modern versions of Android do not publish information about what is in the foreground, for privacy and security reasons. – CommonsWare Dec 22 '17 at 13:41
  • @avezraj I tried with that and on this line: List processes = ProcessManager.getRunningForegroundApps(getApplicationContext()); It cant find the class ProccessManager, it should be in the library but now it's not. – f.trajkovski Dec 25 '17 at 08:43

2 Answers2

0

This code will help you

ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
        Log.d("topActivity", "CURRENT Activity ::" + taskInfo.get(0).topActivity.getClassName());
        ComponentName componentInfo = taskInfo.get(0).topActivity;

        PackageManager packageManager = getApplicationContext().getPackageManager();
        ApplicationInfo appInfo;
        try {
            appInfo = packageManager.getApplicationInfo( componentInfo.getPackageName(), 0);
        } catch (final PackageManager.NameNotFoundException e) {
            appInfo = null;
        }
        String appName = (String) (appInfo != null ? packageManager.getApplicationLabel(appInfo) : "(unknown)");


        Log.e("App Name",""+appName);
RajatN
  • 223
  • 1
  • 8
  • This is the same as i have it and it is not working. Again the result is com.sec.android.app.launcher.activities.LauncherActivity – f.trajkovski Dec 25 '17 at 08:42
0
import android.app.ActivityManager;
import android.app.Service;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;

public class MyBackGroundService extends Service {

    private static MyBackGroundService sMyService;
    private Handler handler;


    @Override
    public void onCreate() {
        super.onCreate();
        sMyService = this;
        handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                printCurrentTask();
                handler.postDelayed(this,60);
            }
        },60);

    }

    public IBinder onBind(Intent intent) {

        return null;
    }

    public static String getForegroundPackageName() {
        return foregroundPackageName;
    }

    private String printCurrentTask() {
        String currentApp = "NULL";
        if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            UsageStatsManager usm = (UsageStatsManager)this.getSystemService("usagestats");
            long time = System.currentTimeMillis();
            List<UsageStats> appList = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY,  time - 1000*1000, time);
            if (appList != null && appList.size() > 0) {
                SortedMap<Long, UsageStats> mySortedMap = new TreeMap<Long, UsageStats>();
                for (UsageStats usageStats : appList) {
                    mySortedMap.put(usageStats.getLastTimeUsed(), usageStats);
                }
                if (mySortedMap != null && !mySortedMap.isEmpty()) {
                    currentApp = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
                }
            }
        } else {
            ActivityManager am = (ActivityManager)this.getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningAppProcessInfo> tasks = am.getRunningAppProcesses();
            currentApp = tasks.get(0).processName;
        }

        Log.d("Top App ******", "Current Top Running App is: " + currentApp);
        return currentApp;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        handler.removeCallbacks(null);
    }
}

add this permision for Usage stats

<uses-permission
        android:name="android.permission.PACKAGE_USAGE_STATS"
        tools:ignore="ProtectedPermissions"/>

even you to ask user to enable the permision if not enabled it will not work

import android.app.AppOpsManager;
import android.app.usage.UsageStatsManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.RequiresApi;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

import java.util.List;

public class MainActivity extends AppCompatActivity {

    Intent backGroundService;

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        backGroundService = new Intent(MainActivity.this, MyBackGroundService.class);
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                checkIfAppUsageAccess();
            }
        });

    }


    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    void checkIfAppUsageAccess(){
        boolean granted = false;
        AppOpsManager appOps = (AppOpsManager) this
                .getSystemService(Context.APP_OPS_SERVICE);
        int mode = appOps.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS,
                android.os.Process.myUid(), getPackageName());

        if (mode == AppOpsManager.MODE_DEFAULT) {
            granted = (checkCallingOrSelfPermission(android.Manifest.permission.PACKAGE_USAGE_STATS) == PackageManager.PERMISSION_GRANTED);
        } else {
            granted = (mode == AppOpsManager.MODE_ALLOWED);
        }
        if (Build.VERSION.SDK_INT >= 21 && !granted) {
            UsageStatsManager mUsageStatsManager = (UsageStatsManager) getSystemService(Context.USAGE_STATS_SERVICE);
            long time = System.currentTimeMillis();
            List stats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000 * 10, time);

            if (stats == null || stats.isEmpty()) {
                Intent intent = new Intent();
                intent.setAction(Settings.ACTION_USAGE_ACCESS_SETTINGS);
                startActivity(intent);
            }
        } else {
            startService(backGroundService);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopService(backGroundService);
    }
}

This code will work for android lollipop as well as below versions

avez raj
  • 2,055
  • 2
  • 22
  • 37