Create list of all installed apps
1. This post describes how to create an app which shows a list of all installed apps.
2. In main.xml add a RecyclerView.
3. Switch on AppCompat and design.
4. Create a custom view recycler_item.xml. In this put an ImageView imageview1, and put three TextViews text_label, text_package, and text_category.
5. For RecyclerView select recycler_item.xml as Custom View.
6. Create a Map List maplist.
7. Add following imports.
import android.content.pm.PackageManager;
import android.content.pm.ApplicationInfo;
8. In onCreate, get all apps and add to maplist.
PackageManager pm = this.getPackageManager();
List<ApplicationInfo> apps = pm.getInstalledApplications(PackageManager.GET_META_DATA);
for (ApplicationInfo ai : apps) {
int category = ApplicationInfo.CATEGORY_UNDEFINED;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
category = ai.category;
}
HashMap<String, Object> map = new HashMap<>();
map.put("name", ai.loadLabel(pm).toString());
map.put("package", ai.packageName);
map.put("icon", ai.loadIcon(pm));
map.put("category", category);
maplist.add(map);
}
Then set the maplist as RecyclerView custom view data.
9. Create a more block (of type String) with name getCategoryName [m.Integer category]
_getCategoryName(Integer _category)
Put following codes in it.
switch (_category) {
case ApplicationInfo.CATEGORY_GAME: return "Game";
case ApplicationInfo.CATEGORY_AUDIO: return "Audio";
case ApplicationInfo.CATEGORY_VIDEO: return "Video";
case ApplicationInfo.CATEGORY_IMAGE: return "Image";
case ApplicationInfo.CATEGORY_SOCIAL: return "Social";
case ApplicationInfo.CATEGORY_NEWS: return "News";
case ApplicationInfo.CATEGORY_MAPS: return "Maps";
case ApplicationInfo.CATEGORY_PRODUCTIVITY: return "Productivity";
case ApplicationInfo.CATEGORY_ACCESSIBILITY: return "Accessibility";
default: return "Undefined";
}
10. Add event RecyclerView onBindCustomView. Get the app name, package name, category and icon from the maplist and display them.
The codes used to display the category and icon are given below.
int category= (int)maplist.get((int)_position).get("category");
binding.textCategory.setText(_getCategoryName(category));
Object drawableObject = maplist.get((int)_position).get("icon");
if (drawableObject instanceof Drawable) {
Drawable drawable = (Drawable) drawableObject;
binding.imageview1.setImageDrawable(drawable);
}
11. Save and run the project.





Comments
Post a Comment