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;
}
Related
**i found thishow to get running applications icon on android programmatically on how we show icons and names of running application but idont know what the type of icons.add(ico);and name.add("" + pName); are so can some on help me what should i do to make it run **
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);
}
}
}
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...
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.
I am trying to check if my app is running already if the user is trying to enter it again.
it is possible if one app Launched anther one and the user entering with a mobile to the second one, and will be 2 instance.
my launcher app that starts the original one looks like that :
Intent i = new Intent(Intent.ACTION_MAIN);
PackageManager manager = getPackageManager();
i = manager.getLaunchIntentForPackage("com.test.vayo");
i.addCategory(Intent.CATEGORY_LAUNCHER);
startActivity(i);
On my original code I am trying to check if there is 2 instance but always get true on this code
if (processName == null) {
return false;
}
ActivityManager manager = (ActivityManager) context.getSystemService(context.ACTIVITY_SERVICE);
List<RunningAppProcessInfo> processes = manager.getRunningAppProcesses();
for (RunningAppProcessInfo process : processes) {
if (processName.equals(process.processName)) {
return true;
}
}
return false;
the proccessName taken from this code, the pid is from android.os.Process.myPid():
private String getAppName(int pID)
{
String processName = "";
ActivityManager am = (ActivityManager)context.getSystemService(context.ACTIVITY_SERVICE);
List l = am.getRunningAppProcesses();
Iterator i = l.iterator();
PackageManager pm = context.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;
}
hope you can tell whats wrong why I am getting always true on my first block of code.
thanks a lot!!
I want to get icons of my all installed apps. Can I get that icons using package manager? Is there any function for it? Or any other way to get icons of all installed apps in bitmap?
Thanks!
try {
String pkg = "com.app.my";//your package name
Drawable icon = getContext().getPackageManager().getApplicationIcon(pkg);
imageView.setImageDrawable(icon);
} catch (PackageManager.NameNotFoundException ne) {
}
Check here for more details.
Above answers are pretty good.
Your Question is:- Get icons of all installed apps in android?
you want list of install apps icon
Here is the code which help you to get install apps list with Application (icons,packages names).
**Declare variable in your Activity**
private CustomAppListAdapter customAppListAdapter;
private ArrayList<AppListMain> appListMainArrayList;
private AppListMain appListMain;
Just call below function loadApps() in your Activity onCreate()
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_app_list);
loadApps();
}
public void loadApps() {
try {
packageManager = getPackageManager();
appListMainArrayList = new ArrayList<>();
Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> resolveInfoList = packageManager.queryIntentActivities(intent, 0);
for (ResolveInfo resolveInfo : resolveInfoList) {
AppListMain appListMain = new AppListMain();
appListMain.setAppIcon(resolveInfo.activityInfo.loadIcon(packageManager));
appListMain.setAppName(resolveInfo.loadLabel(packageManager).toString());
appListMain.setAppPackage(resolveInfo.activityInfo.packageName);
appListMainArrayList.add(appListMain);
}
} catch (Exception e) {
e.printStackTrace();
}
}
Here is Link for reference
OR
You can download custom launcher code from My Github repository
I find it the easiest way:
private List<ResolveInfo> installedApps() {
final Intent main_intent = new Intent(Intent.ACTION_MAIN, null);
main_intent.addCategory(Intent.CATEGORY_LAUNCHER);
return package_manager.queryIntentActivities(main_intent, 0);
}
Now to get the icons, use this:
for(ResolveInfo ri : installedApps()) {
// to get drawable icon --> ri.loadIcon(package_manager)
}
Try this way: Make a class called PackageInformation:
public class PackageInformation {
private Context mContext;
public PackageInformation(Context context) {
mContext = context;
}
class InfoObject {
public String appname = "";
public String pname = "";
public String versionName = "";
public int versionCode = 0;
public Drawable icon;
public void InfoObjectAggregatePrint() { //not used yet
Log.v(appname, appname + "\t" + pname + "\t" + versionName + "\t" + versionCode);
}
}
private ArrayList < InfoObject > getPackages() {
ArrayList < InfoObject > apps = getInstalledApps(false);
final int max = apps.size();
for (int i = 0; i < max; i++) {
apps.get(i).prettyPrint();
}
return apps;
}
public ArrayList < InfoObject > getInstalledApps(boolean getSysPackages) {
ArrayList < InfoObject > res = new ArrayList < InfoObject > ();
List < PackageInfo > packs = mContext.getPackageManager().getInstalledPackages(0);
for (int i = 0; i < packs.size(); i++) {
PackageInfo p = packs.get(i);
if ((!getSysPackages) && (p.versionName == null)) {
continue;
}
InfoObject newInfo = new InfoObject();
newInfo.appname = p.applicationInfo.loadLabel(mContext.getPackageManager()).toString();
newInfo.pname = p.packageName;
newInfo.versionName = p.versionName;
newInfo.versionCode = p.versionCode;
newInfo.icon = p.applicationInfo.loadIcon(mContext.getPackageManager());
res.add(newInfo);
}
return res;
}
}
tuck this away somewhere and now to access the info from your working Activity class do this:
PackageInformation androidPackagesInfo = new PackageInformation(this);
ArrayList < InfoObject > appsData = androidPackagesInfo.getInstalledApps(true);
for (InfoObject info: appsData) {
Toast.makeText(MainActivity.this, info.appname, 2).show();
Drawable somedrawable = info.icon;
}
Here below is the code with which you can get the icons of all installed Apps.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
try {
// try getting the properly colored launcher icons
LauncherApps launcher = (LauncherApps) this.getSystemService(LAUNCHER_APPS_SERVICE);
List<LauncherActivityInfo> activityList = launcher.getActivityList(packageName, android.os.Process.myUserHandle());
drawable = activityList.get(0).getBadgedIcon(0);
} catch (Exception e) {
}
}
if (drawable == null) {
try {
getPackageManager().getApplicationIcon(packageName);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
}