How to find the currently running applications programmatically in Android? - java

I am very new to Android. I am working on application that must get the information about the applications currently running on foreground.
It means if user launches any applications, my application should capture the launched application information, by the time my application shouldn't interrupt launched application.
Example: If user launches browser application my application should print browser application information on log.
How can I do this?

ActivityManager activity_manager = (ActivityManager) context
.getSystemService(Activity.ACTIVITY_SERVICE);
ActivityManager has method getRunningTasks(int). ActivityManager seems to be the solution you are searching for.
final ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
final List<RunningTaskInfo> recentTasks = activityManager.getRunningTasks(Integer.MAX_VALUE);
for (int i = 0; i < recentTasks.size(); i++)
{
Log.d("Executed app", "Application executed : " +recentTasks.get(i).baseActivity.toShortString()+ "\t\t ID: "+recentTasks.get(i).id+"");
}
Also, have a look at following thread:
See Android recent task executed by the user

You can use something similar to this:
ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> tasks = activityManager.getRunningTasks(Integer.MAX_VALUE);
for (int i = 0; i < tasks.size(); i++) {
Log.d("Running task", "Running task: " + tasks.get(i).baseActivity.toShortString() + "\t\t ID: " + tasks.get(i).id);
}

This code will provide the current acitvity logcat
Process logcatProc;
List <String> progs = new ArrayList <String>();
progs.add("logcat");
progs.add("-v");
progs.add(mFormat.getValue());
if (mBuffer != Buffer.MAIN) {
progs.add("-b");
progs.add(mBuffer.getValue());
}
progs.add("*:" + mLevel);
logcatProc = Runtime.getRuntime()
.exec(progs.toArray(new String[0]));
mReader = new BufferedReader(new InputStreamReader(
logcatProc.getInputStream()), 1024);
String line;
while (mRunning && (line = mReader.readLine()) != null) {
if (!mRunning) {
break;
}
if (line.length() == 0) {
continue;
}
if (mIsFilterPattern) {
if (mFilterPattern != null && !mFilterPattern.matcher(line).find()) {
continue;
}
} else {
if (mFilter != null && !line.toLowerCase().contains(mFilter.toLowerCase())) {
continue;
}
}
synchronized (mLogCache) {
mLogCache.add(line);
}
}

ActivityManager.getRunningTasks(int) has been deprecated since API 21, for security reasons. You can use ActivityManager.RunningTaskInfo() to at least get the task info for the current task that this activity is running in (though some fields of RunningTaskInfo(), but not the whole method, are deprecated from API 29).
See Google's docs for more info on RunningTaskInfo().

Related

How to get the packagename of the app that is running in the foreground on an Amazon firetv stick 4K Max?

I’m messing around with this problem for a long time and I’m very clueless how to get this going.
I want to create an app for the Amazon firetv stick 4k max (Android 9 - API level 28), that monitors if one specific app is in the foreground (or gets opened).
Do you have any ideas how to get the packagename of the app that is currently running in the foreground and that's actually working on an Amazon firetv stick 4K Max?
I would really appreciate your help!
I have found a way that works for other Android 9 devices by using the UsageStatsManager, but that does not seem to work for the stick.
Here is what I tried:
public String packageInForeground() {
// Get the UsageStatsManager
UsageStatsManager usageStatsManager = (UsageStatsManager) getSystemService(Context.USAGE_STATS_SERVICE);
// Get the usage events for the last 5 seconds
long currentTime = System.currentTimeMillis();
List<UsageStats> usageStatsList = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_BEST, currentTime - 5000, currentTime);
// Find the latest usage event
UsageStats latestUsageStats = null;
if (usageStatsList != null) {
for (UsageStats usageStats : usageStatsList) {
if (latestUsageStats == null || usageStats.getLastTimeUsed() > latestUsageStats.getLastTimeUsed()) {
latestUsageStats = usageStats;
}
}
}
// Get the package name of the current foreground app
String currentForegroundApp = latestUsageStats != null ? latestUsageStats.getPackageName() : "";
Log.d("Service", "Current foreground app: " + currentForegroundApp);
return currentForegroundApp;
}
There is also a way to use the ActivityManager, but it will only show my own packagename if my own app is in the foreground, but does not show the packagename of other apps, if I open them.
Here is what I tried:
public String packageInForeground() {
ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> runningAppProcesses = activityManager.getRunningAppProcesses();
String packageName = "";
if (runningAppProcesses != null && runningAppProcesses.size() > 0) {
for (ActivityManager.RunningAppProcessInfo processInfo : runningAppProcesses) {
if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
packageName = processInfo.processName.split(":")[0];
Log.d("LockService", "Package Name: " + packageName);
break;
}
}
}
return packageName;
}

How to get Top Activity name of own App

In MainActivity I want to know the current Top Activity opened inside App.
For pre-lollipop I used following
ActivityManager am = (ActivityManager)this.getSystemService(Context.ACTIVITY_SERVICE);
ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
On other posts I found, I should use:
getAppTasks() and gettaskinfo
But I am not able to find any complete example demonstrating how to use the above. Any help is thankful. Regards.
Edit:
Current code:
if (Build.VERSION.SDK_INT >= 23) {
cn = am.getAppTasks().get(0).getTaskInfo().topActivity;
}else{
cn = am.getRunningTasks(1).get(0).topActivity;
}
am.getRunningTasks is deprecated in API 21. And am.getAppTasks#topActivity is available in API 23. So updated question is how to handle it for API 21 and 22.
ActivityManager mgr = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
if (mgr != null) {
List<ActivityManager.AppTask> tasks = mgr.getAppTasks();
String className;
if (tasks != null && !tasks.isEmpty()) {
className = tasks.get(0).getTaskInfo().topActivity.getClassName();
}
}
Credits go to https://www.intertech.com/Blog/android-5-api-changes-getapptasks/

How to count number of times any application opened in my android mobile?

I want to develop an android application where it counts the number of times I have opened another application. Say it should count a number of times I have opened Whatsapp or may be Facebook. How can I achieve this through another android application? How to observe the activity, behavior of other applications in android.
first
1. create a db ( local android SQLite)
then
2. get a list of all the installed applications on the device.Use Android Package Manager with getInstalledApplications()
PackageManager pm = getPackageManager();
List<ApplicationInfo> packages = pm.getInstalledApplications(PackageManager.GET_META_DATA);
for (ApplicationInfo packageInfo : packages) {
Log.d("Installed Apps", "Installed package :" + packageInfo.packageName + " Launch Activity :" + pm.getLaunchIntentForPackage(packageInfo.packageName));
}
save package names and launcher activities in your db
get list of recently launched apps and increment the counter of your db or what you like to do
ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RecentTaskInfo> recentTasks = activityManager.getRecentTasks(Integer.MAX_VALUE,ActivityManager.RECENT_WITH_EXCLUDED);
for (int i = 0; i < recentTasks.size(); i++)
{
String LocalApp = recentTasks.get(i).baseIntent.toString();
int indexPackageNameBegin = LocalApp.indexOf("cmp=")+4;
int indexPackageNameEnd = LocalApp.indexOf("/", indexPackageNameBegin);
String pckge = LocalApp.substring(indexPackageNameBegin, indexPackageNameEnd);
Log.d("Executed app", "Application executed : " +pckge);
}

Get number of installed apps on an Android device?

I'm making an Android launcher as an introduction to making Android apps for myself, and part of my design requires me to know how many apps are installed on a user's device, and preferably count only the ones which are normal apps that can be launched. I wish to store this number of apps in a global, integer variable. With only this goal in mind, what is the simplest way of just retrieving this number as that variable?
You could use the getInstalledApplications() method of PackageManager.
From the documentation:
Return a List of all application packages that are installed on the
device. If flag GET_UNINSTALLED_PACKAGES has been set, a list of all
applications including those deleted with DONT_DELETE_DATA (partially
installed apps with data directory) will be returned.
Something like this should work:
int numberOfInstalledApps = getPackageManager(0).getInstalledApplications().size();
To filter out the system apps you could do something like this:
int numberOfNonSystemApps = 0;
List<ApplicationInfo> appList = getPackageManager().getInstalledApplications(0);
for(ApplicationInfo info : appList) {
if((info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
numberOfNonSystemApps++;
}
}
The all non-system apps have a launch Intent so you just need to fetch the list of all apps and check, how many of them has a launch intent or if not then that app will be a system app.The list of all apps can easily be retrieved by package manager and then we go through the information of all apps while looking for the available launch intent.
As suggested by Darshan Patel : #Brad Larson♦
PackageManager pm = getPackageManager();
int nonSysAppsCount=0;
List<ApplicationInfo> packages = pm.getInstalledApplications(PackageManager.GET_META_DATA);
for(ApplicationInfo packageInfo:packages){
if( pm.getLaunchIntentForPackage(packageInfo.packageName) != null ){
String currAppName = pm.getApplicationLabel(packageInfo).toString();
nonSysAppsCount++;
//This app is a non-system app
}
else{
//System App
}
}
If you are looking for the non-system applications installed on a given device, you can do the following :
public static ArrayList<String> getInstalledApps() {
ArrayList<String> appList = new ArrayList<>();
List<PackageInfo> packList = getPackageManager().getInstalledPackages(0);
for (int i=0; i < packList.size(); i++) {
PackageInfo packInfo = packList.get(i);
if ( (packInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
String appName = packInfo.applicationInfo.loadLabel(getPackageManager()).toString();
appList.add(appName);
Log.e("App >" + Integer.toString(i), appName);
}
}
return appList;
}
So, you can the list by doing :
int number = getInstalledApps().size();
Additionally, you can start any of the applications by calling :
Intent myIntent = new Intent(Intent.ACTION_MAIN, null);
myIntent.addCategory(Intent.CATEGORY_LAUNCHER);
List appsList = context.getPackageManager().queryIntentActivities(myIntent, 0);

How can I get the list of paused/cached acitvities which I see when the home-button is long-pressed?

When I long-press the home button on my phone, I can see a list of activities that I've recently launched. When I start another activity, Android caches/pauses the old activity.
I'd like to get the list of recently launched activities but I can't seem to figure out how. I dug through StackOverflow and the Android SDK documentation of ActivityManager and came up with these two snippets:
ActivityManager mgrActivity = (ActivityManager) this.getSystemService( ACTIVITY_SERVICE );
System.out.println("getRunningTasks: " + mgrActivity.getRunningTasks(Integer.MAX_VALUE).size());
System.out.println("getRecentTasks: " + mgrActivity.getRecentTasks(Integer.MAX_VALUE, ActivityManager.RECENT_WITH_EXCLUDED).size());
Neither of these show me the correct number of activities that I've recently launched. Both these calls return larger values than number of activities shown when I long-press the home button. Can anyone point out what I'm doing wrong?
I tried this to get the name of the activites:
ActivityManager mgrActivity = (ActivityManager) this.getSystemService( ACTIVITY_SERVICE );
for (RunningTaskInfo run : mgrActivity.getRunningTasks(Integer.MAX_VALUE)) {
System.out.println(run.topActivity.getPackageName());
}
for (RecentTaskInfo run : mgrActivity.getRecentTasks(Integer.MAX_VALUE, ActivityManager.RECENT_IGNORE_UNAVAILABLE)) {
if (run.origActivity != null) {
System.out.println(run.origActivity.getPackageName());
} else {
System.out.println(run.id);
}
}
This returns the correct number of recent activities. It's funny how I haven't found this solution elsewhere.
ActivityManager mgrActivity = (ActivityManager) this.getSystemService( ACTIVITY_SERVICE );
for (RecentTaskInfo run : mgrActivity.getRecentTasks(Integer.MAX_VALUE, ActivityManager.RECENT_IGNORE_UNAVAILABLE)) {
if (run.baseIntent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
System.out.println(run.baseIntent.toString());
}
}

Categories