How to get running package names for Android L - java

So we all know that the getRecentTasks() and getRunningTasks() on ActivityManager are now deprecated and will return a reduced result set on Android L and higher devices.
Alternative to getRunningTasks in Android L
https://code.google.com/p/android-developer-preview/issues/detail?id=29
However, I am trying to find a solution to keep my App Locker app alive on Android L. I need the package name of the top Activity in order to show the lock screen when the users opens/launches the locked app.
It is very similar to this app: https://play.google.com/store/apps/details?id=com.domobile.applock&hl=en
Currently I am using this code:
ActivityManager mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> RunningTask = mActivityManager
.getRunningTasks(1);
ActivityManager.RunningTaskInfo ar = RunningTask.get(0);
String activityOnTop = ar.topActivity.getPackageName();
But it won't work in Android L, so I am not sure what exactly to do...
How can I implement something like this in Android L?

Unfortunately, there is no equivalent in Android 5.0: it is not possible to get the top most activity, nor is it possible get any callback when a new application/activity is launched in realtime.

please refer this link.
i hope it will helpful to you, in my project it work. thanks.

Try this line of code for Android L
ActivityManager activityManager = (ActivityManager) getSystemService (Context.ACTIVITY_SERVICE);
String packageName = activityManager.getRunningAppProcesses().get(0).processName;
and please note that this works only for Lollipop devices .. If you want any platform support then add the following code.
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP)
{
String packageName = activityManager.getRunningAppProcesses().get(0).processName;
}
else if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP)
{
String packageName = ProcessManager.getRunningForegroundApps(getApplicationContext()).get(0).getPackageName();
}
else
{
String packageName = activityManager.getRunningTasks(1).get(0).topActivity.getPackageName();
}

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