Get foreground package name in Android 6 - android

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;
}

Related

How to show window when user click on uninstall button of any app

I'm working an app called 'Prevent Uninstall', in this app user creates 4 digit pin and I'm going to save this pin in sharedpreferences. My requirement is when user clicks uninstall button of any application a popup or window should be displayed to confirm the pin which is already created in my application. So is it possible?, if possible please help me, i got stuck at this point.
hello guys finally i have found a solution below..
first get the current activity on foreground
public boolean isConcernedAppIsInForeground() {
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> task = manager.getRunningTasks(5);
if (Build.VERSION.SDK_INT <= 20) {
if (task.size() > 0) {
ComponentName componentInfo = task.get(0).topActivity;
for (int i = 0; pakageName != null && i < pakageName.size(); i++) {
if (componentInfo.getPackageName().equals("com.google.android.packageinstaller")) {
currentApp_for = pakageName.get(i);
return true;
}
}
}
} else {
for (int i = 0; pakageName != null && i < pakageName.size(); i++) {
if (retriveNewApp().equals("com.google.android.packageinstaller")) {
currentApp_for = pakageName.get(i);
Log.e("DSSDSDCSDC", currentApp_for + " LLLLLL::::");
return true;
}
}
}
return false;
}
To get the current activity on foreground above api level 21+ use this code
private String retriveNewApp() {
String currentApp_for_ = null;
if (Build.VERSION.SDK_INT >= 21) {
UsageStatsManager usm = (UsageStatsManager) this.getSystemService(Context.USAGE_STATS_SERVICE);
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<>();
for (UsageStats usageStats : applist) {
mySortedMap.put(usageStats.getLastTimeUsed(), usageStats);
}
if (mySortedMap != null && !mySortedMap.isEmpty()) {
currentApp_for_ = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
}
Log.e(">>>>>>>>>><<<", "Current App in foreground is: " + currentApp_for_);
} else {
Log.e("CCC>>C>C>C>", "User not given the permission: " + currentApp_for_);
}
}
return currentApp_for_;
}
Important permission
<uses-permission
android:name="android.permission.PACKAGE_USAGE_STATS"
tools:ignore="ProtectedPermissions" />
now check the current activity is in foreground or not using service
if (isConcernedAppIsInForeground()) {
if (!currentApp.matches(previousApp)) {
// if matches do your activity here..
startActivity(newIntent(context,Draw_Lock.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
previousApp = currentApp;
}
}
}
Note: When user clicks on uninstall button of any app alert dialog popups which is known as 'com.google.android.packageinstaller' activity check weather this activity is in foreground or not using service class

getRunningAppProcesses() doesn't work in API 22 and above [duplicate]

It seems Google finally closed all doors for getting the current foreground application package.
After the Lollipop update, which killed getRunningTasks(int maxNum) and thanks to this answer, I used this code to get the foreground application package since Lollipop:
final int PROCESS_STATE_TOP = 2;
RunningAppProcessInfo currentInfo = null;
Field field = null;
try {
field = RunningAppProcessInfo.class.getDeclaredField("processState");
} catch (Exception ignored) {
}
ActivityManager am = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningAppProcessInfo> appList = am.getRunningAppProcesses();
for (RunningAppProcessInfo app : appList) {
if (app.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND &&
app.importanceReasonCode == 0 ) {
Integer state = null;
try {
state = field.getInt( app );
} catch (Exception ignored) {
}
if (state != null && state == PROCESS_STATE_TOP) {
currentInfo = app;
break;
}
}
}
return currentInfo;
Android 5.1.1 and above (6.0 Marshmallow), it seems, killed getRunningAppProcesses() as well. It now returns a list of your own application package.
UsageStatsManager
We can use the new UsageStatsManager API as described here but it doesn't work for all applications. Some system applications will return the same package
com.google.android.googlequicksearchbox
AccessibilityService (December 2017: Going to be banned for use by Google)
Some applications use AccessibilityService (as seen here) but it has some disadvantages.
Is there another way of getting the current running application package?
To get a list of running processes on Android 1.6 - Android 6.0 you can use this library I wrote: https://github.com/jaredrummler/AndroidProcesses The library reads /proc to get process info.
Google has significantly restricted access to /proc in Android Nougat. To get a list of running processes on Android Nougat you will need to use UsageStatsManager or have root access.
Click the edit history for previous alternative solutions.
private String printForegroundTask() {
String currentApp = "NULL";
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
UsageStatsManager usm = (UsageStatsManager)this.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)this.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> tasks = am.getRunningAppProcesses();
currentApp = tasks.get(0).processName;
}
Log.e("adapter", "Current App in foreground is: " + currentApp);
return currentApp;
}
Use this method for getting foreground task.
U will need an System Permission "android:get_usage_stats"
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 user enable this in setting -> Security-> app with usage access. After that u will get foreground task. Similar process Clean matser by Cheetahamobile
google play link
Take a look at https://github.com/ricvalerio/foregroundappchecker, it might be what you need. Provides sample code, and takes away the pain of having to implement cross version foreground detector.
Here are two samples:
AppChecker appChecker = new AppChecker();
String packageName = appChecker.getForegroundApp();
Or regularly check:
AppChecker appChecker = new AppChecker();
appChecker
.when("com.other.app", new AppChecker.Listener() {
#Override
public void onForeground(String packageName) {
// do something
}
)
.when("com.my.app", new AppChecker.Listener() {
#Override
public void onForeground(String packageName) {
// do something
}
)
.other(new AppChecker.Listener() {
#Override
public void onForeground(String packageName) {
// do something
}
)
.timeout(1000)
.start(this);
Google limited this functionality for system apps only. As been reported in a bug ticket, you will need the REAL_GET_TASKS permission to access there.
Applications must now have ...permission.REAL_GET_TASKS to be able to
get process information for all applications. Only the process
information for the calling application will be returned if the app
doesn't have the permission. Privileges apps will temporarily be able
to get process information for all applications if they don't have the
new permission, but have deprecated ...permission.GET_TASKS Also,only
system apps can acquire the REAL_GET_TASKS permission.
Just throwing out a potential optimization to what I imagine is a heavily copy-pasted bit of code for detecting the top-most application on Android M.
This
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
UsageStatsManager usm = (UsageStatsManager)this.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();
}
}
}
Can be simplified to this
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
UsageStatsManager usm = (UsageStatsManager) context.getSystemService(
Context.USAGE_STATS_SERVICE);
long time = System.currentTimeMillis();
List<UsageStats> appStatsList = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY,
time - 1000 * 1000, time);
if (appStatsList != null && !appStatsList.isEmpty()) {
currentApp = Collections.max(appStatsList, (o1, o2) ->
Long.compare(o1.getLastTimeUsed(), o2.getLastTimeUsed())).getPackageName();
}
}
I found myself using this code in a 2 second loop, and wondered why I was using a complex solution that was O(n*log(n)) when a more simple solution was available in Collections.max() which is O(n).
public class AccessibilityDetectingService extends AccessibilityService {
#Override
protected void onServiceConnected() {
super.onServiceConnected();
//Configure these here for compatibility with API 13 and below.
AccessibilityServiceInfo config = new AccessibilityServiceInfo();
config.eventTypes = AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED;
config.feedbackType = AccessibilityServiceInfo.FEEDBACK_GENERIC;
if (Build.VERSION.SDK_INT >= 16)
//Just in case this helps
config.flags = AccessibilityServiceInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS;
setServiceInfo(config);
}
#Override
public void onAccessibilityEvent(final AccessibilityEvent event) {
if (event == null ) {
return;
} else if(event.getPackageName() == null && event.getClassName() == null){
return;
}
if (activityInfo != null){
Log.d("CurrentActivity", componentName.flattenToShortString());
}
}
private ActivityInfo tryGetActivity(ComponentName componentName) {
try {
return getPackageManager().getActivityInfo(componentName, 0);
} catch (PackageManager.NameNotFoundException e) {
return null;
}
}
#Override
public void onInterrupt() {
}
}
}//`enter code here`uses-permission android:name="android.permission.BIND_ACCESSIBILITY_SERVICE" />
<uses-permission android:name="android.permission.GET_TASKS" />
Then start the service and app accessibility on in your device
setting->accessibility->App
on that service.
Please try to use getRunningServices() instead of getRunningAppProcesses() method.
ActivityManager mActivityManager = (ActivityManager) getSy stemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningServiceInfo> appProcessInfoList = mActivityManager.getRunningServices(Integer.MAX_VALUE);

How to get Top Activity in Android 5.0 +

I'm using below code to get Top Activity
private String getTopPackageName() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
return activityManager.getRunningTasks(1).get(0).topActivity.getPackageName();
} else {
final List<ActivityManager.RunningAppProcessInfo> pis = activityManager.getRunningAppProcesses();
for (ActivityManager.RunningAppProcessInfo pi : pis) {
if (pi.pkgList.length == 1) return pi.pkgList[0];
}
}
return "";
}
It word on API<21 but API>=21 it return "" :(
How to get that?
I will try:
private void 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_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)this.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> tasks = am.getRunningAppProcesses();
currentApp = tasks.get(0).processName;
}
Log.e(TAG, "Current App in foreground is: " + currentApp);
}
BUT return NULL :( please help me! thanks
getRunningTasks() is deprecated in API level 21(Lollipop)
As alternate you can do like this
List<ActivityManager.RunningAppProcessInfo> task = manager.getRunningAppProcesses();
ComponentName componentInfo = task.get(0).importanceReasonComponent;
String packageName = componentInfo.getPackageName()
Note:
this method is only intended for debugging and presenting task management user interfaces. This should never be used for core logic in an application, such as deciding between different behaviors based on the information found here.
Refer the doc
UPDATE:
ActivityManager manager = (ActivityManager) MainActivity.this.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> task = manager.getRunningAppProcesses();
ActivityManager.RunningAppProcessInfo runningAppProcessInfo = null;
for(ActivityManager.RunningAppProcessInfo singleTask : task){
if(singleTask.importanceReasonComponent !=null){
runningAppProcessInfo = singleTask;
break;
}
}
if(runningAppProcessInfo!=null) {
ComponentName componentInfo = runningAppProcessInfo.importanceReasonComponent;
String packageName = componentInfo.getPackageName();
Log.d("myPackageName", packageName);
}
You can also use Accessibility Services but for that you need to redirect your users to the Accessibility Settings to turn it on. Sample code is below to get the package of the app which has been just opened or in your case the top activity.
public class MyAccessibilityService extends AccessibilityService {
#Override
public void onAccessibilityEvent(AccessibilityEvent event) {
String packageName = event.getPackageName();
}
}
you need use permission "PACKAGE_USAGE_STATS" for UsageStatsManager:
"This API requires the permission android.permission.PACKAGE_USAGE_STATS, which is a system-level permission and will not be granted to third-party apps. However, declaring the permission implies intention to use the API and the user of the device can grant permission through the Settings application."
Refer:https://developer.android.com/reference/android/app/usage/UsageStatsManager.html

Android M: How can I get the current foreground activity package name(from a service)

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

Different package when app is getting launched (Lollipop or above issue)

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));
}

Categories

Resources