我想通过我的服务知道前台应用的名称。
我已经使用了下面的代码,但是它们只提供我的应用名称或家。 但是当我打开facebook Messenger或其他应用程序时无法获得名称。
这是我在服务中使用的代码。
ActivityManager.RunningAppProcessInfo result=null, info=null;
ActivityManager activityManager = (ActivityManager) Verifying_Service.this.getSystemService( Context.ACTIVITY_SERVICE );
PackageManager pm1 = Verifying_Service.this.getPackageManager();
List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
for(ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
if(appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
CharSequence c = null;
try {
c = pm1.getApplicationLabel(pm1.getApplicationInfo(appProcess.processName, PackageManager.GET_META_DATA));
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
Toast.makeText(Verifying_Service.this, appProcess.processName, Toast.LENGTH_SHORT).show();
//Log.i("Foreground App", "package: " + appProcess.processName + " App: " + c.toString());
}
}
我也尝试过这个
ActivityManager am = (ActivityManager) Verifying_Service.this.getSystemService(ACTIVITY_SERVICE);
// The first in the list of RunningTasks is always the foreground task.
ActivityManager.RunningTaskInfo foregroundTaskInfo = am.getRunningTasks(5).get(0);
String foregroundTaskPackageName = foregroundTaskInfo .topActivity.getPackageName();
PackageManager pm = Verifying_Service.this.getPackageManager();
PackageInfo foregroundAppPackageInfo = null;
try {
foregroundAppPackageInfo = pm.getPackageInfo(foregroundTaskPackageName, 0);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
String foregroundTaskAppName = foregroundAppPackageInfo.applicationInfo.loadLabel(pm).toString();
Toast.makeText(Verifying_Service.this, foregroundTaskAppName, Toast.LENGTH_SHORT).show();
先谢谢您。 目前,我正在使用棉花糖android版本。