From a background service, I am getting a launcher app package name.
Code used:
private String printForegroundTask() {
String currentApp = "NULL";
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
UsageStatsManager usm = (UsageStatsManager) this.getSystemService(Context.USAGE_STATS_SERVICE);
long time = System.currentTimeMillis();
List<UsageStats> appList = usm.queryUsageStats(UsageStatsManager.INTERVAL_YEARLY, 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);
currentApp = am.getRunningTasks(1).get(0).topActivity.getPackageName();
}
return currentApp;
}
When I launched the Downloads app, I am getting package name com.android.documentsui, but this package belong to Documents app.
Documents App: com.android.documentsui
Download Manager App: com.android.providers.downloads
Downloads App: com.android.providers.downloads.ui
I am facing this issue for Lollipop.
I checked the App lock application. I found that if Downloads app is locked and launched I see the Documents as the app name instead of Downloads,
i.e. app lock application is recognizing that all above defined packages belongs to same app.
Any idea regarding this?
use this code so that you can get the package name of list of apps installed in moblie
final PackageManager pm = getPackageManager();
//get a list of installed apps.
List packages = pm.getInstalledApplications(PackageManager.GET_META_DATA);
for (ApplicationInfo packageInfo : packages) {
Log.d(TAG, "Installed package :" + packageInfo.packageName);
Log.d(TAG, "Launch Activity :" + pm.getLaunchIntentForPackage(packageInfo.packageName));
}
Related
I am trying to get a list of currently running apps on my phone. Here is the code I am using:
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
UsageStatsManager usm = (UsageStatsManager)this.getSystemService(Context.USAGE_STATS_SERVICE);
long time = System.currentTimeMillis();
List<UsageStats> appList = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 10000*10000, time);
if (appList != null && appList.size() == 0) {
Log.d("Executed app", "######### NO APP FOUND ##########" );
}
if (appList != null && appList.size() > 0) {
SortedMap<Long, UsageStats> mySortedMap = new TreeMap<Long, UsageStats>();
for (UsageStats usageStats : appList) {
Log.d("Executed app", "usage stats executed : " +usageStats.getPackageName() + "\t\t ID: ");
mySortedMap.put(usageStats.getLastTimeUsed(), usageStats);
}
if (mySortedMap != null && !mySortedMap.isEmpty()) {
String currentApp = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
}
}
}
Here I have set the permission as well:
<uses-permission
android:name="android.permission.PACKAGE_USAGE_STATS"
tools:ignore="ProtectedPermissions" />
It does not detect any app usage. I have tried some other things on stackoverflow but nothing seems to work. I have even read somewhere that the ability for apps to monitor other apps running on the phone has been removed completely in the newer phones. Would greatly appreciate any help!
The problem is that your application does not have the system permission of android:get_usage_stats.
You can use the below code to check if you have the permission:
public static boolean needPermissionForBlocking(Context context){
try {
PackageManager packageManager = context.getPackageManager();
ApplicationInfo applicationInfo = packageManager.getApplicationInfo(context.getPackageName(), 0);
AppOpsManager appOpsManager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
int mode = appOpsManager.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, applicationInfo.uid, applicationInfo.packageName);
return (mode != AppOpsManager.MODE_ALLOWED);
} catch (PackageManager.NameNotFoundException e) {
return true;
}
}
If you do not have the permission then the user must enable this permission by going to Settings -> Security-> Apps with usage access, and then adding your application. Your code should then work fine.
I want to know how to get the package name when I open an app, for instance when I open Facebook I should get its package name and when I open another app I should get its package name how do I do this?
I does not show you the package name when you open the specific app, but you can use this code to list the package names of all apps installed on your device.
I don't think an Android app can have the privilege to "listen" for the launch of another app. You could only achieve this with a custom ROM.
You can do this with the PackageManager.
final PackageManager manager = getPackageManager();
List<ApplicationInfo> packages = manager.getInstalledApplications(PackageManager.GET_META_DATA);
for (ApplicationInfo info : packages) {
Log.i("Info", "Installed package:" + info.packageName);
}
For get the package name for the running app in Background you need to run one service and call the below method every 100 or 300 milliseconds, it will give you the current running package name. for more detail you can see this link, In this method AndroidUtils you can find in the link.
public String getRecentApps(Context context) {
String topPackageName = "";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
UsageStatsManager mUsageStatsManager = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
long time = System.currentTimeMillis();
UsageEvents usageEvents = mUsageStatsManager.queryEvents(time - 1000 * 30, System.currentTimeMillis() + (10 * 1000));
UsageEvents.Event event = new UsageEvents.Event();
while (usageEvents.hasNextEvent()) {
usageEvents.getNextEvent(event);
}
if (event != null && !TextUtils.isEmpty(event.getPackageName()) && event.getEventType() == UsageEvents.Event.MOVE_TO_FOREGROUND) {
if (AndroidUtils.isRecentActivity(event.getClassName())) {
return event.getClassName();
}
return event.getPackageName();
} else {
topPackageName = "";
}
} else {
ActivityManager am = (ActivityManager) context.getSystemService(context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
ComponentName componentInfo = taskInfo.get(0).topActivity;
// If the current running activity it will return not the package name it will return the activity refernce.
if (AndroidUtils.isRecentActivity(componentInfo.getClassName())) {
return componentInfo.getClassName();
}
topPackageName = componentInfo.getPackageName();
}
return topPackageName;
}
If your app is AppLocker you should call this method more frequent may
be every 100ms then only you can lock other apps.
There is one third party app in playstore ,which shows 'Package Name' along with Activity's name .Find it over here:
https://play.google.com/store/apps/details?id=com.willme.topactivity&hl=en_IN
I use the code below to get the application package name.
But when I swipe the notification bar, it will take the name of the application package running in the notification bar.
Or where applications are updating the new version, it will take the name of the application package.
I tried it on Android 5 get exact results open application package name.
So how to get the name of the application package is currently running on Android open 6
public static String printForegroundTask(Context context) {
String currentApp = "Null";
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
UsageStatsManager usm = (UsageStatsManager) context
.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) context
.getSystemService(Context.ACTIVITY_SERVICE);
currentApp = am.getRunningTasks(1).get(0).topActivity
.getPackageName();
}
return currentApp;
}
How to detect which app has been launched by user in my app i.e my application should get notified when Whatsapp is launched by user even if my app is not running in foreground or background.
hike messenger has achieved same functionality with accessibility service.
How can I solve this problem ?
Thanks in advance!!
Depending on the Android version running your application, you will have to use different methods.
On Pre-Lollipop devices, it is pretty straight-forward:
String[] result = new String[2];
List<ActivityManager.RunningTaskInfo> runningTasks;
ComponentName componentInfo;
runningTasks = activityManager.getRunningTasks(1);
componentInfo = runningTasks.get(0).topActivity;
result[0] = componentInfo.getPackageName();
result[1] = componentInfo.getClassName();
If you are on a Lollipop or newer device, you have to use UsageStatsManager class, which requires your application to be granted specific permissions
//no inspection ResourceType
UsageStatsManager mUsageStatsManager = (UsageStatsManager)context.getSystemService("usagestats");
long time = System.currentTimeMillis();
// We get usage stats for the last 10 seconds
List<UsageStats> stats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000*10, time);
// Sort the stats by the last time used
if(stats != null) {
SortedMap<Long,UsageStats> mySortedMap = new TreeMap<>();
for (UsageStats usageStats : stats) {
mySortedMap.put(usageStats.getLastTimeUsed(),usageStats);
}
if(mySortedMap != null && !mySortedMap.isEmpty()) {
return mySortedMap.get(mySortedMap.lastKey()).getPackageName();
}
}
return null;
This will tell you if your apps has been granted permissions:
try {
PackageManager packageManager = context.getPackageManager();
ApplicationInfo applicationInfo = packageManager.getApplicationInfo(context.getPackageName(), 0);
AppOpsManager appOpsManager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
int mode = appOpsManager.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, applicationInfo.uid, applicationInfo.packageName);
return (mode != AppOpsManager.MODE_ALLOWED);
} catch (PackageManager.NameNotFoundException e) {
return false;
}
And finally this will launch the Android permission granting activity for the user:
Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
activity.startActivity(intent);
Hope that helps
Try this code:
ActivityManager activityManager = (ActivityManager) this.getSystemService( ACTIVITY_SERVICE );
List<RunningAppProcessInfo> procInfos = activityManager.getRunningAppProcesses();
for(int i = 0; i < procInfos.size(); i++)
{
if(procInfos.get(i).processName.equals("put the package name here"))
{
Toast.makeText(getApplicationContext(), "Notify Message", Toast.LENGTH_LONG).show();
}
}
No, this is not really possible using the public SDK.
You can get the current running process by ActivityManager#getRunningAppProcesses But it is definitely impossible to get notified .However, it isn't the most accurate, or efficient method
It is easy to get a list of running tasks from the ActivityManager service on Android L, and the current active task is returned first. But it don't work on Android M any more, the return list only contains my app task. Is there any way to settle it?
My code:
List<ActivityManager.RunningAppProcessInfo> runningAppProcessInfos = activityManager.getRunningAppProcesses();
for (int i = 0; i < runningAppProcessInfos.size(); i++) {
ActivityManager.RunningAppProcessInfo runningAppProcessInfo = runningAppProcessInfos.get(i);
if (runningAppProcessInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
return runningAppProcessInfo.pkgList[0];
}
}
you can use below code and get the current foreground activity package name.
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
UsageStatsManager usm = (UsageStatsManager) 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) getBaseContext().getSystemService(ACTIVITY_SERVICE);
currentApp = am.getRunningTasks(1).get(0).topActivity .getPackageName();
}
Edit
Add this permission in to Manifest file.
<uses-permission android:name="android.permission.GET_TASKS" />
<uses-permission android:name="android.permission.PACKAGE_USAGE_STATS" tools:ignore="ProtectedPermissions" />
Note
Make sure you need to configure custom setting in your device to obtain the output you can config it with Setting > Security > Apps with usage access > Then enable your app permission
Please try this lines in Android M. This worked for me
String packageName = ProcessManager.getRunningForegroundApps(getApplicationContext()).get(0).getPackageName();
check below link for other android platform support.
https://stackoverflow.com/a/36660429/4554069