If you need to monitor your android device activities and you want to identify the current opened application name in that case you can simply create the method given below in your utility class. And call it whenever you want to get the current opened application name.
public static String getOpenedApp(Context context)
{
final PackageManager manager = context.getPackageManager();
final ActivityManager tasksManager = (ActivityManager) context.getSystemService(context.ACTIVITY_SERVICE);
final List<ActivityManager.RecentTaskInfo> recentTasks = tasksManager.getRecentTasks(5, 0);
final int count = 1;
for (int i = count - 1; i >= 0;)
{
final Intent intent = recentTasks.get(i).baseIntent;
if (Intent.ACTION_MAIN.equals(intent.getAction()) && !intent.hasCategory(Intent.CATEGORY_HOME))
{
final ResolveInfo resolveInfo = manager.resolveActivity(intent, 0);
if (resolveInfo == null) {
return null;
}
final ActivityInfo activityInfo = resolveInfo.activityInfo;
return activityInfo.loadLabel(manager).toString();
}
else
{
return "Home Screen";
}
}
return null;
}
If you get Home Screen that mean device Home Screen is opened.
Dont forget to add this permission to your AndroidManifest.xml
< uses-permission android:name="android.permission.GET_TASKS"/> ;
Hope it might help you.
Thanks :)
0 Comment(s)