Search code examples
androidandroid-jetpack-composeandroid-jetpack

How to get icons of installed apps?


There are a lot of Java sample codes, but I couldn't find any results for Jetpack Compose.
I have a ViewModel and it returns a list of package names. I want to show the application icons.

A similar problem has occurred before, but coudn't find a solution from the answers.

class MalwareListViewModel : ViewModel() {
    private val malwareList = mutableListOf<String>()
    fun getMalwareList(): List<String> {
        return malwareList
    }
}

Solution

  • You can get a ApplicationInfo object from an app package name using getApplicationInfo() and then use that to load the app icon:

    val malwareIcons = mutableListOf<Drawable>()
    for (packageName in malwareList) {
        try {
            val appInfo = packageManager.getApplicationInfo(packageName, 0);  // may throw NameNotFoundException
            val appIcon: Drawable = packageManager.getApplicationIcon(appInfo)
            malwareIcons.add(appIcon)
        } catch(NameNotFoundException n) {
            Log.e("MalwareViewModel", "Package Name $packageName not found.")
        }
    }
    

    The list malwareIcons then contains all icons of the package names in your malwareList.