How to get package name after lollipop version in android - android

I have tried this below code for getting forground application package name but it is getting my own app application package name only. other application packagte name will be null.it means it is returning null ...how can i get package name.. is there any other way. I know getrunningappprocess is blocked by google.
(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
List<ActivityManager.RunningAppProcessInfo> tasks = manager.getRunningAppProcesses();
String mpackageName = tasks.get(0).processName;
UsageStatsManager usage = (UsageStatsManager) this.getSystemService(this.USAGE_STATS_SERVICE);
long time = System.currentTimeMillis();
List<UsageStats> appList = usage.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000 * 1000, time);
if (appList != null && appList.size() > 0) {
SortedMap<Long, UsageStats> runningTask = new TreeMap<Long, UsageStats>();
for (UsageStats usageStats : appList) {
runningTask.put(usageStats.getLastTimeUsed(), usageStats);
}
if (!runningTask.isEmpty() && runningTask != null) {
mpackageName = runningTask.get(runningTask.lastKey()).getPackageName();
}
}
for (int i = 0; pakageName != null && i < pakageName.size(); i++) {
Log.e("AppCheck", "comfor2 : " + mpackageName + " pak2 : " + pakageName.get(i));
if (mpackageName.equals(pakageName.get(i))) {
currentApp = pakageName.get(i);
return true;
}
}
}

Get class name from below method...
public static void classNameRunning(Context context) {
boolean isInBackground = true;
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
for (String activeProcess : processInfo.pkgList) {
if (activeProcess.equals(context.getPackageName())) {
// print log for class name
}
}
}
}
} else {
List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
ComponentName componentInfo = taskInfo.get(0).topActivity;
if (componentInfo.getPackageName().equals(context.getPackageName())) {
Log.w("Package name ==> ",componentInfo.getPackageName());
}
}
}

public static HashSet<String> getRunningApps(Context context) {
final HashSet<String> hashSet = new HashSet<String>();
final ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
final PackageManager packageManager = context.getPackageManager();
List<RunningTaskInfo> runningTasks = activityManager.getRunningTasks(Integer.MAX_VALUE);
for (RunningTaskInfo runningTaskInfo : runningTasks) {
String packageName = runningTaskInfo.baseActivity.getPackageName();
try {
String appName = packageManager.getApplicationInfo(packageName, 0).loadLabel(packageManager).toString();
hashSet.add(appName);
} catch (NameNotFoundException exception) {
// handle Exception
}
}
return hashSet;
}

Related

How Do "App Lock" app work internally?

I need to develop app just like android App lock that opens password activity when app assigned application get launch. I have read below question but didn't find proper solution.
I just want to ask that what service or method they are using? how to know about any other app launch event?
In my current implementation, I have added a service and in MyService, I have added a timer to check currentApp and then I am comparing current app to assigned app.
I don't like this approach because timer takes lot of battery as well as device get slow.
public void isForeground(String myPackage){
String currentApp="";
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();
}
processCurrentApp(currentApp,myPackage);
}
Any one can help me in this? Thanks in advance.
To get current active apps try
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(pakageName.get(i))) {
currentApp = pakageName.get(i);
return true;
}
}
}
} else {
String mpackageName = manager.getRunningAppProcesses().get(0).processName;
UsageStatsManager usage = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
long time = System.currentTimeMillis();
List<UsageStats> stats = usage.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, 0, time);
if (stats != null) {
SortedMap<Long, UsageStats> runningTask = new TreeMap<Long, UsageStats>();
for (UsageStats usageStats : stats) {
runningTask.put(usageStats.getLastTimeUsed(), usageStats);
}
if (runningTask.isEmpty()) {
Log.d(TAG,"isEmpty Yes");
mpackageName = "";
}else {
mpackageName = runningTask.get(runningTask.lastKey()).getPackageName();
Log.d(TAG,"isEmpty No : "+mpackageName);
}
}
for (int i = 0; pakageName != null && i < pakageName.size(); i++) {
if (mpackageName.equals(pakageName.get(i))) {
currentApp = pakageName.get(i);
return true;
}
}
}
return false;
}
Check this open source project: https://github.com/amitshekhariitbhu/AppLock/

How to get application name on various Android device?

I am using bellow code to get application name in Android. For example on Galaxy S4; if the phone is in Home screen, and the below function returns the TouchWiz home. However, on Note 4, the function returns Google Home. Do we have any way to maintain the application name or detect the name depending on the device name? Currently, I save the Home screen in a list corresponding to the device name. However, I think it will not cover all possible case.
public String getAppName() {
String foregroundProcess = "";
ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(ACTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
UsageStatsManager mUsageStatsManager = (UsageStatsManager) getSystemService(USAGE_STATS_SERVICE);
long time = System.currentTimeMillis();
List<UsageStats> stats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000 * 1000, time);
// Sort the stats by the last time used
if (stats != null) {
SortedMap<Long, UsageStats> mySortedMap = new TreeMap<Long, UsageStats>();
for (UsageStats usageStats : stats) {
mySortedMap.put(usageStats.getLastTimeUsed(), usageStats);
}
if (mySortedMap != null && !mySortedMap.isEmpty()) {
String topPackageName = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
foregroundProcess = topPackageName;
}
}
} else {
#SuppressWarnings("deprecation")
ActivityManager.RunningTaskInfo foregroundTaskInfo = activityManager.getRunningTasks(1).get(0);
foregroundProcess = foregroundTaskInfo.topActivity.getPackageName();
}
//Convert package name to application name
final PackageManager pm = getApplicationContext().getPackageManager();
ApplicationInfo ai;
try {
ai = pm.getApplicationInfo(foregroundProcess, 0);
} catch (final PackageManager.NameNotFoundException e) {
ai = null;
}
String applicationName = (String) (ai != null ? pm.getApplicationLabel(ai) : "(unknown)");
return applicationName;
}

How to `getTopActivity` name or get currently running application package name in lollipop?

I am creating a app lock application. How to get current running task in lollipop? getRunningTaskinfo method is deprecated in lollipop API, then how to overcome this problem?
try this:
ActivityManager mActivityManager =(ActivityManager)this.getSystemService(Context.ACTIVITY_SERVICE);
if(Build.VERSION.SDK_INT > 20){
String mPackageName = mActivityManager.getRunningAppProcesses().get(0).processName;
}
else{
String mpackageName = mActivityManager.getRunningTasks(1).get(0).topActivity.getPackageName();
}
we can get using UsageStats:
public static String getTopAppName(Context context) {
ActivityManager mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
String strName = "";
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
strName = getLollipopFGAppPackageName(context);
} else {
strName = mActivityManager.getRunningTasks(1).get(0).topActivity.getClassName();
}
} catch (Exception e) {
e.printStackTrace();
}
return strName;
}
private static String getLollipopFGAppPackageName(Context ctx) {
try {
UsageStatsManager usageStatsManager = (UsageStatsManager) ctx.getSystemService("usagestats");
long milliSecs = 60 * 1000;
Date date = new Date();
List<UsageStats> queryUsageStats = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, date.getTime() - milliSecs, date.getTime());
if (queryUsageStats.size() > 0) {
Log.i("LPU", "queryUsageStats size: " + queryUsageStats.size());
}
long recentTime = 0;
String recentPkg = "";
for (int i = 0; i < queryUsageStats.size(); i++) {
UsageStats stats = queryUsageStats.get(i);
if (i == 0 && !"org.pervacio.pvadiag".equals(stats.getPackageName())) {
Log.i("LPU", "PackageName: " + stats.getPackageName() + " " + stats.getLastTimeStamp());
}
if (stats.getLastTimeStamp() > recentTime) {
recentTime = stats.getLastTimeStamp();
recentPkg = stats.getPackageName();
}
}
return recentPkg;
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
// TO ENABLE USAGE_STATS
// Declare USAGE_STATS permisssion in manifest
<uses-permission
android:name="android.permission.PACKAGE_USAGE_STATS"
tools:ignore="ProtectedPermissions" />
Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
startActivity(intent);
Best solution of get Running app in API 21 or up is below try it.
this work for me
private String retriveNewApp() {
if (VERSION.SDK_INT >= 21) {
String currentApp = null;
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 = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
}
}
Log.e(TAG, "Current App in foreground is: " + currentApp);
return currentApp;
}
else {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
String mm=(manager.getRunningTasks(1).get(0)).topActivity.getPackageName();
Log.e(TAG, "Current App in foreground is: " + mm);
return mm;
}
}
You can use the AccessibilityService to get current Running app.
Accessibility Service provides the onAccessibilityEvent event.
Following is some sample code.
#Override
public void onAccessibilityEvent(AccessibilityEvent event) {
if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
if (event.getPackageName() != null && event.getClassName() != null) {
Log.d("Foreground App", event.getPackageName().toString());
}
}
}
You can find more info about Accessibility Service here
Are you sure? As I can see according to the latest Android docs, LOLLIPOP update doesnt allow you to know any info about other apps than your own!?
http://developer.android.com/reference/android/app/ActivityManager.html
You can see that all those methods are deprecated!
according to this ; the following code worked perfectly for me :
MOVE_TO_FOREGROUND and MOVE_TO_BACKGROUND added in sdk 21 and deprecated in sdk 29
ACTIVITY_RESUMED and ACTIVITY_PAUSED added in sdk 29
public static String getTopPkgName(Context context) {
String pkgName = null;
UsageStatsManager usageStatsManager = (UsageStatsManager) context
.getSystemService(Context.USAGE_STATS_SERVICE);
final long timeTnterval= 1000 * 600;
final long endTime = System.currentTimeMillis();
final long beginTime = endTime - timeTnterval;
final UsageEvents myUsageEvents = usageStatsManager .queryEvents(beginTime , endTime );
while (myUsageEvents .hasNextEvent()) {
UsageEvents.Event myEvent = new UsageEvents.Event();
myUsageEvents .getNextEvent(myEvent );
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
switch (myEvent .getEventType()) {
case UsageEvents.Event.ACTIVITY_RESUMED:
pkgName = myEvent .getPackageName();
break;
case UsageEvents.Event.ACTIVITY_PAUSED:
if (myEvent .getPackageName().equals(pkgName )) {
pkgName = null;
}
}
}else {
switch (event.getEventType()) {
case UsageEvents.Event.MOVE_TO_FOREGROUND:
pkgName = myEvent .getPackageName();
break;
case UsageEvents.Event.MOVE_TO_BACKGROUND:
if (myEvent .getPackageName().equals(pkgName )) {
pkgName = null;
}
}
}
}
return pkgName ;
}
Try this.. This worked for me.
ActivityManager activityManager = (ActivityManager) getSystemService (Context.ACTIVITY_SERVICE);
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();
}
#Manish Godhani's answer (https://stackoverflow.com/a/38829083/8179249) works very well, but you have to give the right permissions for this !
See the two first points of that answer : https://stackoverflow.com/a/42560422/8179249
It works for me (before adding permissions I was getting 'null' too), as shown below :
Can be achieved like this.....
ActivityManager am =(ActivityManager)context.getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
ActivityManager.RunningTaskInfo task = tasks.get(0); // current task
ComponentName rootActivity = task.baseActivity;
rootActivity.getPackageName();//*currently active applications package name*
For lollipop:
ActivityManager mActivityManager =(ActivityManager)this.getSystemService(Context.ACTIVITY_SERVICE);
if(Build.VERSION.SDK_INT > 20){
String activityName =mActivityManager.getRunningAppProcesses().get(0).processName;
}
else{
String activityName = mActivityManager.getRunningTasks(1).get(0).topActivity.getPackageName();
}
for complete example check this out...

how to get running applications icon on android programmatically

Below here is my code but i am getting default android launcher icon for all running applications:
PackageManager pm = getPackageManager();
ActivityManager am1 = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> processes = am1.getRunningTasks(Integer.MAX_VALUE);
if (processes != null) {
for (int k = 0; k < processes.size(); k++) {
// String pkgName = app.getPackageName();
String packageName = processes.get(k).topActivity
.getPackageName();
Drawable ico = null;
try
{
String pName = (String) pm.getApplicationLabel(pm
.getApplicationInfo(packageName,
PackageManager.GET_META_DATA));
ico = pm.getApplicationIcon(pName);
}
catch (NameNotFoundException e)
{
Log.e("ERROR", "Unable to find icon for package '"
+ packageName + "': " + e.getMessage());
}
icons.put(processes.get(k).topActivity.getPackageName(),ico);
}
just replace this line
ico = pm.getApplicationIcon(pName);
to this
ico = getApplicationInfo().loadIcon(getPackageManager());
EDITED full code :
public void getAllICONS() {
PackageManager pm = getPackageManager();
ActivityManager am1 = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> processes = am1
.getRunningTasks(Integer.MAX_VALUE);
if (processes != null) {
for (int k = 0; k < 5; k++) {
// String pkgName = app.getPackageName();
String packageName = processes.get(k).topActivity
.getPackageName();
Log.e("packageName-->", "" + packageName);
Drawable ico = null;
try {
String pName = (String) pm.getApplicationLabel(pm
.getApplicationInfo(packageName,
PackageManager.GET_META_DATA));
name.add("" + pName);
ApplicationInfo a = pm.getApplicationInfo(packageName,
PackageManager.GET_META_DATA);
ico = getPackageManager().getApplicationIcon(
processes.get(k).topActivity.getPackageName());
getPackageManager();
Log.e("ico-->", "" + ico);
} catch (NameNotFoundException e) {
Log.e("ERROR", "Unable to find icon for package '"
+ packageName + "': " + e.getMessage());
}
// icons.put(processes.get(k).topActivity.getPackageName(),ico);
icons.add(ico);
}
}
}
above code is show you icons like:
To retrieve the app icon, you can use the getApplicationIcon() method of the PackageManger.
In your case, since you are retriving the icon of the running apps, you can do something like:
final ActivityManager am = (ActivityManager) getSystemService(Activity.ACTIVITY_SERVICE);
final PackageManager pm = getPackageManager();
List<ActivityManager.RunningTaskInfo> runningTasks;
try {
runningTasks = am.getRunningTasks(100);
}
catch ( SecurityException e ) {
runningTasks = new ArrayList<ActivityManager.RunningTaskInfo>();
//e.printStackTrace();
}
Drawable icon;
for ( ActivityManager.RunningTaskInfo task : runningTasks ) {
final String packageName = task.topActivity.getPackageName();
try {
icon = pm.getApplicationIcon(packageName);
}
catch ( PackageManager.NameNotFoundException e ) {
//e.printStackTrace();
}
}
Otherwise, even better, you may use the other implementation of getApplicationIcon(), thus:
ApplicationInfo ai;
try {
ai = pm.getApplicationInfo(packageName, PackageManager.GET_META_DATA);
} catch ( PackageManager.NameNotFoundException e ) {
ai = null;
//e.printStackTrace();
}
if ( ai != null ) {
icon = pm.getApplicationIcon(ai);
}
PS: In any case, please note that getRunningTasks() will never return null, but an empty list at most.

How to get app package name by pid?

String callerPackage = getAppNameByPID(getContext(), Binder.getCallingPid());
private String getAppNameByPID(Context context, int callingPid) {
//How ?
....
}
my questions:
How to get app package name by pid?
Each process can hold multiple packages, so it looks like:
private String[] getPackageNames(int pid)
{
ActivityManager activityManager = (ActivityManager)getContext().getSystemService(Activity.ACTIVITY_SERVICE);
List<RunningAppProcessInfo> runningAppProcesses = activityManager.getRunningAppProcesses();
for(RunningAppProcessInfo runningAppProcessInfo : runningAppProcesses)
{
try
{
if(runningAppProcessInfo.pid == pid)
{
return runningAppProcessInfo.pkgList;
}
}
catch(Exception e)
{
}
}
return null;
}
Hello you can try out this code, it works fine for me.
private String getAppName(int pID)
{
String processName = "";
ActivityManager am = (ActivityManager)this.getSystemService(ACTIVITY_SERVICE);
List l = am.getRunningAppProcesses();
Iterator i = l.iterator();
PackageManager pm = this.getPackageManager();
while(i.hasNext())
{
ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo)(i.next());
try
{
if(info.pid == pID)
{
CharSequence c = pm.getApplicationLabel(pm.getApplicationInfo(info.processName, PackageManager.GET_META_DATA));
//Log.d("Process", "Id: "+ info.pid +" ProcessName: "+ info.processName +" Label: "+c.toString());
//processName = c.toString();
processName = info.processName;
}
}
catch(Exception e)
{
//Log.d("Process", "Error>> :"+ e.toString());
}
}
return processName;
}

Categories

Resources