How to get a list of installed android applications and pick one to run
Asked Answered
N

24

366

I asked a similar question to this earlier this week but I'm still not understanding how to get a list of all installed applications and then pick one to run.

I've tried:

Intent intent = new Intent(ACTION_MAIN);
intent.addCategory(CATEGORY_LAUNCHER);

and this only shows application that are preinstalled or can run the ACTION_MAIN Intent type.

I also know I can use PackageManager to get all the installed applications, but how do I use this to run a specific application?

Nicolanicolai answered 23/4, 2010 at 2:7 Comment(2)
How can you only get the information about the picked app in the list ?Eugeniaeugenics
Are you trying to start a specific set of apps, like, a gallery app. Or a set of apps that can offer you a service, like getting a file?Nitin
I
295

Following is the code to get the list of activities/applications installed on Android :

Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> pkgAppsList = context.getPackageManager().queryIntentActivities( mainIntent, 0);

You will get all the necessary data in the ResolveInfo to start a application. You can check ResolveInfo javadoc here.

Incommodious answered 23/4, 2010 at 6:21 Comment(10)
How can I start one of these? I got the activityInfo inside ResolveInfo, but I can't manage to start it.Typeset
Nevermind, found it. I should create a new Intent using the full class name (package + class).Typeset
How can you only get the information about the picked app in the list ?Eugeniaeugenics
I wanted to understand the android /play store policy about the my app reading and storing a list of all apps, and potentially communicating with a server. Is there any guidelines?Goldstein
@Incommodious how can we find the default file manager's package name from the list? Any idea/solution ?Sexism
@Goldstein Did u happen to find the guidelines regarding this ?Azov
VersionName? Did I miss?Vereen
can I filter paid and unpaid apps?Well
can we access getPackageManager from a service?Cornew
this solution didn't work on target SDK 31Acidimetry
A
468

Here's a cleaner way using the PackageManager

final PackageManager pm = getPackageManager();
//get a list of installed apps.
List<ApplicationInfo> packages = pm.getInstalledApplications(PackageManager.GET_META_DATA);

for (ApplicationInfo packageInfo : packages) {
    Log.d(TAG, "Installed package :" + packageInfo.packageName);
    Log.d(TAG, "Source dir : " + packageInfo.sourceDir);
    Log.d(TAG, "Launch Activity :" + pm.getLaunchIntentForPackage(packageInfo.packageName)); 
}
// the getLaunchIntentForPackage returns an intent that you can use with startActivity() 

More info here http://qtcstation.com/2011/02/how-to-launch-another-app-from-your-app/

Andeee answered 23/2, 2011 at 22:10 Comment(14)
Works gr8. But when tried this on Android 4.0.3, nothing gets printed !! Any clue ??Genetics
Make sure you are not filtering out debug log statements.Cabriolet
This code is working however, do you have any idea on how to put those list of application in a ListView?Pythoness
@Pythoness im doing the same. read this here - vogella.com/tutorials/AndroidListView/article.htmlMcleod
@DavidT. I already figured it out. Now, I'm working on how can I access those installed app in order to create a shortcut inside my App. Is that possible?Pythoness
@Pythoness i think so. you should be able to get each app's icons, and then launch them based on the intent that they specified to accept. you can ask as a question, and tag me for me to answer. i don't have much space here (commenting) to answer.Mcleod
@DavidT. here's my question. I really need your help. #21371991Pythoness
This works great but can take a few seconds depending on the number of apps installed. Is there a faster way to load this?Yiyid
@Nelson Ramirez is it possible to find memory size consumed by each installed app ? how can i find ?Ephod
I have tried this on Andriod 6.0 it still shows an application as installed after it has been uninstalled.Applied
qtfstation link isn't working. I'm wondering if anyone could shed light on what the GET_META_DATA constant does, specifically?Fantinlatour
@user10186832 are you sure you didn't input MATCH_UNINSTALLED_PACKAGES?Pearce
@Pearce I think it depends on what the uninstall procedure doesApplied
Yes if you do pm uninstall -k (I think it is) then it keeps the userdata, meaning it should show up even when uninstalled, but to my understanding only if you input MATCH_UNINSTALLED_PACKAGES...Pearce
I
295

Following is the code to get the list of activities/applications installed on Android :

Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> pkgAppsList = context.getPackageManager().queryIntentActivities( mainIntent, 0);

You will get all the necessary data in the ResolveInfo to start a application. You can check ResolveInfo javadoc here.

Incommodious answered 23/4, 2010 at 6:21 Comment(10)
How can I start one of these? I got the activityInfo inside ResolveInfo, but I can't manage to start it.Typeset
Nevermind, found it. I should create a new Intent using the full class name (package + class).Typeset
How can you only get the information about the picked app in the list ?Eugeniaeugenics
I wanted to understand the android /play store policy about the my app reading and storing a list of all apps, and potentially communicating with a server. Is there any guidelines?Goldstein
@Incommodious how can we find the default file manager's package name from the list? Any idea/solution ?Sexism
@Goldstein Did u happen to find the guidelines regarding this ?Azov
VersionName? Did I miss?Vereen
can I filter paid and unpaid apps?Well
can we access getPackageManager from a service?Cornew
this solution didn't work on target SDK 31Acidimetry
A
67

Another way to filter on system apps (works with the example of king9981):

/**
 * Return whether the given PackageInfo represents a system package or not.
 * User-installed packages (Market or otherwise) should not be denoted as
 * system packages.
 * 
 * @param pkgInfo
 * @return
 */
private boolean isSystemPackage(PackageInfo pkgInfo) {
    return ((pkgInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
}
Absonant answered 13/12, 2011 at 3:16 Comment(9)
This is the best answer for filtering out system apps.Knotts
But I t filters appliaction like settings , maps , or ... , how to list them tooArbela
The "? true : false" part of your return statement is redundantAquamanile
simplify return ((pkgInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);Pronunciation
how to filter paid apps?Well
Thumbs down for using a bitwise operator with a != :(Inmate
@Ondrej Sotolar What do you suggest? I see there are unneeded parentheses, but I don't understand your comment.Absonant
It's just a matter of style. For me, bitwise operators break readability big time. Instead of just flying through a simple if statement I have to actually stop and think about the implications of the operator.Inmate
This is not working in case of samsung devices. becasuse it is counting facebook app as systems signed apppSiler
G
63

Here a good example:

class PInfo {
    private String appname = "";
    private String pname = "";
    private String versionName = "";
    private int versionCode = 0;
    private Drawable icon;
    private void prettyPrint() {
        Log.v(appname + "\t" + pname + "\t" + versionName + "\t" + versionCode);
    }
}

private ArrayList<PInfo> getPackages() {
    ArrayList<PInfo> apps = getInstalledApps(false); /* false = no system packages */
    final int max = apps.size();
    for (int i=0; i<max; i++) {
        apps.get(i).prettyPrint();
    }
    return apps;
}

private ArrayList<PInfo> getInstalledApps(boolean getSysPackages) {
    ArrayList<PInfo> res = new ArrayList<PInfo>();        
    List<PackageInfo> packs = getPackageManager().getInstalledPackages(0);
    for(int i=0;i<packs.size();i++) {
        PackageInfo p = packs.get(i);
        if ((!getSysPackages) && (p.versionName == null)) {
            continue ;
        }
        PInfo newInfo = new PInfo();
        newInfo.appname = p.applicationInfo.loadLabel(getPackageManager()).toString();
        newInfo.pname = p.packageName;
        newInfo.versionName = p.versionName;
        newInfo.versionCode = p.versionCode;
        newInfo.icon = p.applicationInfo.loadIcon(getPackageManager());
        res.add(newInfo);
    }
    return res; 
}
Giule answered 8/11, 2011 at 15:28 Comment(2)
How do you execute one of those if you need to? I mean, can you get the Intent?Rainier
Great. Thanks for your answer. I have used your answer in my application and I have a small problem with the size of icon. most of them are normal and some of them are very big or small. How can I fix that. Do you have any idea? thanksCompatible
A
42

Getting list of installed non-system apps

public static void installedApps()
{
    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();
            Log.e("App № " + Integer.toString(i), appName);
        }
    }
}
Alienee answered 21/4, 2013 at 8:49 Comment(0)
C
21

To filter on sytem based apps :

private boolean isSystemPackage(ResolveInfo ri) {
    return (ri.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
}
Chit answered 10/1, 2011 at 11:44 Comment(0)
F
19

To get all installed apps you can use Package Manager

List<PackageInfo> apps = getPackageManager().getInstalledPackages(0);

To run an app, you can use its package name

Intent launchApp = getPackageManager().getLaunchIntentForPackage(“package name”)
startActivity(launchApp);

For more detail you can read this blog http://codebucket.co.in/android-get-list-of-all-installed-apps/

Forefinger answered 16/3, 2012 at 5:43 Comment(1)
This is more to the point. We can set a proper check by finding out our required app.Glucosuria
C
18

context.getPackageManager().getInstalledApplications(PackageManager.GET_META_DATA); Should return the list of all the installed apps but in android 11 it'll only return the list of system apps. To get the list of all the applications(system+user) we need to provide an additional permission to the application i.e

<uses-permission android:name="android.permission.QUERY_ALL_PACKAGES"/>

Caudle answered 20/11, 2020 at 17:29 Comment(1)
small corrections: <uses-permission android:name="android.permission.QUERY_ALL_PACKAGES"/>Naughton
V
15

You can Find the List of installed apps in Android Device by using below code, "packageInfo" Contains Installed Application Information in Device. we can retrive Intent for the application installed from the packageinfo object and by using startactivity(intent), can start application. it is up to you how you organize the UI either Listview or Gridview. so on click event based on position, you can retrive intent object and start activity intent.

final PackageManager pm = getPackageManager();

List<ApplicationInfo> packages = pm.getInstalledApplications(PackageManager.GET_META_DATA);


for (ApplicationInfo packageInfo : packages) 

{
 if(pm.getLaunchIntentForPackage(packageInfo.packageName)!= null &&   

                   !pm.getLaunchIntentForPackage(packageInfo.packageName).equals(""))


{

    System.out.println("Package Name :" + packageInfo.packageName);

    System.out.println("Launch Intent For Package :"   +  
                  pm.getLaunchIntentForPackage(packageInfo.packageName));

    System.out.println("Application Label :"   + pm.getApplicationLabel(packageInfo));

    System.out.println("Application Label :"   + 
                           pm.getApplicationIcon(packageInfo.packageName).toString());

    System.out.println("i : "+i);

    /*if(i==2)

    {
         startActivity(pm.getLaunchIntentForPackage(packageInfo.packageName));

     break;

    }*/

    i++;

}
}
Vernice answered 20/2, 2012 at 10:10 Comment(0)
A
13

I had a requirement to filter out the system apps which user do not really use(eg. "com.qualcomm.service", "update services", etc). Ultimately I added another condition to filter down the app list. I just checked whether the app has 'launcher intent'.

So, the resultant code looks like...

PackageManager pm = getPackageManager();
        List<ApplicationInfo> apps = pm.getInstalledApplications(PackageManager.GET_GIDS);

        for (ApplicationInfo app : apps) {
            if(pm.getLaunchIntentForPackage(app.packageName) != null) {
                // apps with launcher intent
                if((app.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
                    // updated system apps

                } else if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
                    // system apps

                } else {
                    // user installed apps

                }
                appsList.add(app);
            }

        }
Adenosine answered 24/4, 2015 at 19:10 Comment(1)
Thanks. The getLaunchIntentForPackage is very useful to get the apps present in the App Drawer :-)Enthral
S
10

If there are multiple launchers in a one package above code has a problem. Eg: on LG Optimus Facebook for LG, MySpace for LG, Twitter for LG contains in a one package name SNS and if you use above SNS will repeat. After hours of research I came with below code. Seems to work well.

private List<String> getInstalledComponentList()
            throws NameNotFoundException {
        final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
        mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        List<ResolveInfo> ril = getPackageManager().queryIntentActivities(mainIntent, 0);
        List<String> componentList = new ArrayList<String>();
        String name = null;

        for (ResolveInfo ri : ril) {
            if (ri.activityInfo != null) {
                Resources res = getPackageManager().getResourcesForApplication(ri.activityInfo.applicationInfo);
                if (ri.activityInfo.labelRes != 0) {
                    name = res.getString(ri.activityInfo.labelRes);
                } else {
                    name = ri.activityInfo.applicationInfo.loadLabel(
                            getPackageManager()).toString();
                }
                componentList.add(name);
            }
        }
        return componentList;
    }
Sullyprudhomme answered 6/11, 2012 at 4:37 Comment(0)
P
10

Since Android 11 (API level 30), most user-installed apps are not visible by default. You must either statically declare which apps and/or intent filters you are going to get info about in your manifest like this:

<manifest>
    <queries>
        <!-- Explicit apps you know in advance about: -->
        <package android:name="com.example.this.app"/>
        <package android:name="com.example.this.other.app"/>

        <!-- Intent filter signatures that you are going to query: -->
        <intent>
            <action android:name="android.intent.action.SEND" />
            <data android:mimeType="image/jpeg" />
        </intent>
    </queries>
    
    ...
</manifest>

Or require the QUERY_ALL_PACKAGES permission.

After doing the above, the other answers here still apply.

Learn more here:

Pileum answered 18/10, 2020 at 23:13 Comment(0)
T
8

@Jas: I don't have that code anymore, but I've found something close. I've made this to search for "components" of my application, they are just activities with a given category.

private List<String> getInstalledComponentList() {
    Intent componentSearchIntent = new Intent();
    componentSearchIntent.addCategory(Constants.COMPONENTS_INTENT_CATEGORY);
    componentSearchIntent.setAction(Constants.COMPONENTS_INTENT_ACTION_DEFAULT);
    List<ResolveInfo> ril = getPackageManager().queryIntentActivities(componentSearchIntent, PackageManager.MATCH_DEFAULT_ONLY);
    List<String> componentList = new ArrayList<String>();
    Log.d(LOG_TAG, "Search for installed components found " + ril.size() + " matches.");
    for (ResolveInfo ri : ril) {
        if (ri.activityInfo != null) {
            componentList.add(ri.activityInfo.packageName);// + ri.activityInfo.name);
            Log.d(LOG_TAG, "Found installed: " + componentList.get(componentList.size()-1));
        }
    }
    return componentList;
}

I've commented the part where it gets the activity name, but it's pretty straightforward.

Typeset answered 6/2, 2011 at 1:13 Comment(0)
J
7

Clean solution that filter successfuly out system apps

The idea behind this solution is that the main activity of every system app does not have a custom activity icon. This method gives me an excellent result:

 public static Set<PackageInfo> getInstalledApps(Context ctx) {
    final PackageManager packageManager = ctx.getPackageManager();

    final List<PackageInfo> allInstalledPackages = packageManager.getInstalledPackages(PackageManager.GET_META_DATA);
    final Set<PackageInfo> filteredPackages = new HashSet();

    Drawable defaultActivityIcon = packageManager.getDefaultActivityIcon();

    for(PackageInfo each : allInstalledPackages) {
        if(ctx.getPackageName().equals(each.packageName)) {
            continue;  // skip own app
        }

        try {
            // add only apps with application icon
            Intent intentOfStartActivity = packageManager.getLaunchIntentForPackage(each.packageName);
            if(intentOfStartActivity == null)
                continue;

            Drawable applicationIcon = packageManager.getActivityIcon(intentOfStartActivity);
            if(applicationIcon != null && !defaultActivityIcon.equals(applicationIcon)) {
                filteredPackages.add(each);
            }
        } catch (PackageManager.NameNotFoundException e) {
            Log.i("MyTag", "Unknown package name " + each.packageName);
        }
    }

    return filteredPackages;
}
Jokester answered 22/9, 2015 at 9:12 Comment(0)
C
4
private static boolean isThisASystemPackage(Context context, PackageInfo  packageInfo ) {
        try {
            PackageInfo sys = context.getPackageManager().getPackageInfo("android", PackageManager.GET_SIGNATURES);
            return (packageInfo != null && packageInfo.signatures != null &&
                    sys.signatures[0].equals(packageInfo.signatures[0]));
        } catch (NameNotFoundException e) {
            return false;
        }
    }
Cuman answered 25/12, 2012 at 4:29 Comment(0)
T
3

I have another solution:

ArrayList<AppInfo> myAppsToUpdate;

    // How to get the system and the user apps.
    public ArrayList<AppInfo> getAppsToUpdate() {

        PackageManager pm = App.getContext().getPackageManager();
        List<ApplicationInfo> installedApps = pm.getInstalledApplications(0);
        myAppsToUpdate = new ArrayList<AppInfo>();
        for (ApplicationInfo aInfo : installedApps) {

            if ((aInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
                // System apps 
            } else {
                // Users apps
                AppInfo appInfo = new AppInfo();
                appInfo.setAppName(aInfo.loadLabel(pm).toString());
                appInfo.setPackageName(aInfo.packageName);
                appInfo.setLaunchActivity(pm.getLaunchIntentForPackage(aInfo.packageName).toString());
                try {
                    PackageInfo info = pm.getPackageInfo(aInfo.packageName, 0);
                    appInfo.setVersionName(info.versionName.toString());
                    appInfo.setVersionCode("" + info.versionCode);
                    myAppsToUpdate.add(appInfo);
                } catch (NameNotFoundException e) {
                    Log.e("ERROR", "we could not get the user's apps");
                }

            }
        }
        return myAppsToUpdate;
    }
Talithatalk answered 26/5, 2015 at 20:34 Comment(0)
A
3

Get All the apps:

    PackageManager pm = getContext().getPackageManager();
    List<ApplicationInfo> apps = pm.getInstalledApplications(0);

Check if installed app then open:

if((app.flags & (ApplicationInfo.FLAG_UPDATED_SYSTEM_APP | ApplicationInfo.FLAG_SYSTEM)) > 0) {
                String app_package = app.packageName;
Intent launchIntent = context.getPackageManager().getLaunchIntentForPackage(app_package);
context.startActivity(launchIntent);
Amagasaki answered 16/11, 2017 at 12:39 Comment(0)
M
3

This answer is correct an list of installed app show and search feature add.

Kotlin

activity_all_installed_app.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".AllInstalledAppActivity">

    <TextView
        android:id="@+id/totalInstalledApp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/total_Installed_Apps"
        android:textStyle="bold"
        android:textAlignment="center"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:orientation="vertical"
        app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/totalInstalledApp"
        tools:listitem="@layout/installed_app_layout" />
</androidx.constraintlayout.widget.ConstraintLayout>

installed_app_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_margin="4dp"
    android:elevation="6dp"
    android:background="?attr/selectableItemBackground">
    <androidx.cardview.widget.CardView
        android:id="@+id/cardview"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        app:cardCornerRadius="5dp"
        app:cardUseCompatPadding="true"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <ImageView
                android:id="@+id/app_icon"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="8dp"
                android:contentDescription="@string/todo"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent" />

            <TextView
                android:id="@+id/list_app_name"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginStart="8dp"
                android:text="@string/app_name"
                android:textSize="16sp"
                android:textStyle="bold"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toEndOf="@+id/app_icon"
                app:layout_constraintTop_toTopOf="parent" />

            <TextView
                android:id="@+id/app_package"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginStart="8dp"
                android:text="@string/app_package_name"
                android:textStyle="bold"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toEndOf="@+id/app_icon"
                app:layout_constraintTop_toBottomOf="@+id/list_app_name" />
        </androidx.constraintlayout.widget.ConstraintLayout>
    </androidx.cardview.widget.CardView>
</androidx.constraintlayout.widget.ConstraintLayout>

AppModel.kt

import android.graphics.drawable.Drawable

class AppModel(private var name:String, private var icon: Drawable, private var packages:String) {
    fun getName(): String {
        return name
    }

    fun getIcon(): Drawable {
        return icon
    }

    fun getPackages(): String {
        return packages
    }
}

AppAdapter.kt


import android.app.AlertDialog
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.materialsouk.allcodeapp.R
import com.materialsouk.allcodeapp.models.AppModel
import java.util.ArrayList

import android.content.Intent
import android.net.Uri
import android.provider.Settings
import android.widget.Toast


class AppAdapter(private val context: Context, private var appModelList: ArrayList<AppModel>) :
    RecyclerView.Adapter<AppAdapter.ViewHolder>() {


    class ViewHolder(ItemView: View) : RecyclerView.ViewHolder(ItemView) {
        val appNameTxt: TextView = itemView.findViewById(R.id.list_app_name)
        val appPackageNameTxt: TextView = itemView.findViewById(R.id.app_package)
        val appIcon: ImageView = itemView.findViewById(R.id.app_icon)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view: View =
            LayoutInflater.from(parent.context)
                .inflate(R.layout.installed_app_layout, parent, false)
        return ViewHolder(view)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.appNameTxt.text = appModelList[position].getName()
        holder.appIcon.setImageDrawable(appModelList[position].getIcon())
        holder.appPackageNameTxt.text = appModelList[position].getPackages()

        holder.itemView.setOnClickListener {
            val dialogListTitle = arrayOf("Open App", "App Info")
            val builder: AlertDialog.Builder = AlertDialog.Builder(context)
            builder.setTitle("Choose Action")
                .setItems(
                    dialogListTitle
                ) { _, which ->
                    when (which) {
                        0 -> {
                            val intent =
                                context.packageManager.getLaunchIntentForPackage(appModelList[position].getPackages())
                            if (intent != null) {
                                context.startActivity(intent)
                            }else{
                                Toast.makeText(context,"System app is not open for any reason.",Toast.LENGTH_LONG).show()
                            }
                        }
                        1 -> {
                            val intent = Intent()
                            intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
                            intent.data =
                                Uri.parse("package:${appModelList[position].getPackages()}")
                            context.startActivity(intent)
                        }
                    }
                }
            builder.show()
        }

    }

    override fun getItemCount(): Int {
        return appModelList.size
    }
}

This is menu search_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/app_bar_search"
        android:icon="@drawable/ic_search_black_24dp"
        android:title="@string/search"
        app:showAsAction="ifRoom|withText"
        app:actionViewClass="androidx.appcompat.widget.SearchView"/>
</menu>

AllInstalledAppActivity.kt


import android.annotation.SuppressLint
import android.app.Dialog
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.recyclerview.widget.RecyclerView
import com.materialsouk.allcodeapp.models.AppModel

import android.content.pm.PackageInfo

import android.content.pm.ApplicationInfo
import android.os.Handler
import android.os.Looper
import android.view.Menu
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.widget.SearchView
import com.materialsouk.allcodeapp.adapters.AppAdapter
import java.util.*
import kotlin.collections.ArrayList


class AllInstalledAppActivity : AppCompatActivity() {
    private lateinit var recyclerView: RecyclerView
    private lateinit var installedAppsList: ArrayList<AppModel>
    private lateinit var installedAppAdapter: AppAdapter

    @SuppressLint("SetTextI18n")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_all_installed_app)
        recyclerView = findViewById(R.id.recycler_view)
        val loadingDialog = Dialog(this)
        loadingDialog.setContentView(R.layout.loading)
        loadingDialog.window!!.setLayout(
            LinearLayout.LayoutParams.WRAP_CONTENT,
            LinearLayout.LayoutParams.WRAP_CONTENT
        )
        loadingDialog.setCancelable(false)
        installedAppsList = ArrayList()
        loadingDialog.show()
        Handler(Looper.getMainLooper()).postDelayed({
            getInstalledApps()
            loadingDialog.dismiss()
            findViewById<TextView>(R.id.totalInstalledApp).text =
                "${getString(R.string.total_Installed_Apps)} ${installedAppsList.size}"
            installedAppAdapter = AppAdapter(this, installedAppsList)
            recyclerView.adapter = installedAppAdapter
        }, 500)

    }

    @SuppressLint("QueryPermissionsNeeded")
    private fun getInstalledApps(): ArrayList<AppModel> {
        installedAppsList.clear()
        val packs = packageManager.getInstalledPackages(0)
        for (i in packs.indices) {
            val p = packs[i]
            if (!isSystemPackage(p)) {
                val appName = p.applicationInfo.loadLabel(packageManager).toString()
                val icon = p.applicationInfo.loadIcon(packageManager)
                val packages = p.applicationInfo.packageName
                installedAppsList.add(AppModel(appName, icon, packages))
            }
        }
        installedAppsList.sortBy { it.getName().capitalized() }
        return installedAppsList
    }
    private fun String.capitalized(): String {
        return this.replaceFirstChar {
            if (it.isLowerCase())
                it.titlecase(Locale.getDefault())
            else it.toString()
        }
    }
    private fun isSystemPackage(pkgInfo: PackageInfo): Boolean {
        return pkgInfo.applicationInfo.flags and ApplicationInfo.FLAG_SYSTEM != 0
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.search_menu, menu)
        val search = menu.findItem(R.id.app_bar_search)

        val searchView = search.actionView as SearchView
        searchView.maxWidth = android.R.attr.width
        searchView.queryHint = "Search app name or package"
        searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
            override fun onQueryTextSubmit(query: String?): Boolean {
                return false
            }

            @SuppressLint("NotifyDataSetChanged")
            override fun onQueryTextChange(newText: String?): Boolean {
                val appModelArrayList: ArrayList<AppModel> = ArrayList()

                for (i in installedAppsList) {
                    if (i.getName().lowercase(Locale.getDefault()).contains(
                            newText!!.lowercase(
                                Locale.getDefault()
                            )
                        )
                        ||
                        i.getPackages().lowercase(Locale.getDefault()).contains(
                            newText.lowercase(
                                Locale.getDefault()
                            )
                        )
                    ) {
                        appModelArrayList.add(i)
                    }
                }
                installedAppAdapter =
                    AppAdapter(this@AllInstalledAppActivity, appModelArrayList)

                recyclerView.adapter = installedAppAdapter
                installedAppAdapter.notifyDataSetChanged()
                return true
            }
        })

        return super.onCreateOptionsMenu(menu)
    }
}
Milson answered 7/11, 2021 at 11:38 Comment(0)
B
2
fun getInstalledApps(context: Context): List<ApplicationInfo> {
    val result: ArrayList<ApplicationInfo> = arrayListOf()
    val userManager = context.getSystemService(Context.USER_SERVICE) as UserManager
    val launcherApps = context.getSystemService(Context.LAUNCHER_APPS_SERVICE) as LauncherApps

    for (profile in userManager.userProfiles) {
        for (app in launcherApps.getActivityList(null, profile)) {
            result.add(app.applicationInfo)
        }
    }

    return result
}

Add this permission to Manifest File

<uses-permission
        android:name="android.permission.QUERY_ALL_PACKAGES"
        tools:ignore="QueryAllPackagesPermission"/>
Biscay answered 22/2, 2024 at 11:20 Comment(0)
I
0

you can use this :

PackageManager pm = getApplicationContext().getPackageManager();
                List<ResolveInfo> activityList = pm.queryIntentActivities(shareIntent, 0);
                for (final ResolveInfo app : activityList) 
                {
                   if ((app.activityInfo.name).contains("facebook")) 
                   {
                     // facebook  
                   }

                   if ((app.activityInfo.name).contains("android.gm")) 
                   {
                     // gmail  
                   }

                   if ((app.activityInfo.name).contains("mms")) 
                   {
                     // android messaging app
                   }

                   if ((app.activityInfo.name).contains("com.android.bluetooth")) 
                   {
                     // android bluetooth  
                   }
                }
Iy answered 27/2, 2015 at 8:57 Comment(0)
R
0
public static List<ApplicationInfo> getApplications(Context context) {
    return context.getPackageManager().getInstalledApplications(PackageManager.GET_META_DATA);
}
Richey answered 26/4, 2018 at 18:27 Comment(0)
D
0

hope this helps, updated function to get all system, system apps which are updated and user-installed apps.

fun installedAppsAndSystemApps() {
    val packageManager = context.packageManager
    val packList = packageManager.getInstalledPackages(0)
    val installedApps = ArrayList<PackageInfo>()
    val updatedSystemApps = ArrayList<PackageInfo>()
    val systemApps = ArrayList<PackageInfo>()

    for (i in packList.indices) {
        val packInfo = packList[i]
        if (packageManager.getLaunchIntentForPackage(packInfo.packageName) != null) {
            when {
                packInfo.applicationInfo.flags and ApplicationInfo.FLAG_UPDATED_SYSTEM_APP != 0 -> {
                    // updated system apps
                    updatedSystemApps.add(packInfo)
                }
                packInfo.applicationInfo.flags and ApplicationInfo.FLAG_SYSTEM != 0 -> {
                    // system apps
                    systemApps.add(packInfo)
                }
                else -> {
                    // user installed apps
                    installedApps.add(packInfo)
                }
            }
        }
    }
}
Dioptrics answered 16/5, 2023 at 7:9 Comment(0)
D
0

For android version 11 and above please use below permission to show all the installed apps.

<uses-permission android:name="android.permission.QUERY_ALL_PACKAGES"/>
Dramaturgy answered 26/5, 2023 at 9:14 Comment(0)
L
0

Google now provides LauncherApps API for fetching information about all the launchable activities in Android. We can use it to fetch the list of all the apps installed on the device.

Query Permission to be added in AndroidManifest.xml

<uses-permission android:name="android.permission.QUERY_ALL_PACKAGES" />

Method for fetching all the installed apps information.

val launcherApps = context.getSystemService(LauncherApps::class.java)

// Get the list of launcher activity info
val activityList = launcherApps.getActivityList(null, Process.myUserHandle())

// Print total apps count
Log.d("MainActivity", "Total Apps: ${activityList.size}")

getActivityList returns a list of LauncherActivityInfo objects which contains info like first install time, drawable app icon, app label, etc.

Hope it helps!

Luong answered 15/9, 2023 at 14:45 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.