The consensus is that passing a Drawable from one activity to another using Intent is a very bad idea (maybe cause it's slow?). The general recommendation is to pass the Uri of an image instead of the image itself, however this method doesn't apply when your images are stored in an array or list. For example I have a list of Drawables that contains the icons of all the apps a user has. When I need to pass any of these icons to another activity there's no Uri available. So what I did was make the list available in an Application class, meaning I had a class that extended Application and which was called Notifications:
public class Notifications extends Application {
private List<ResolveInfo> packages;
public static final String CHANNEL_ID = "exampleServiceChannel";
@Override
public void onCreate() { //using onCreate will help you show notifications before any activity begins
super.onCreate();
createNotificationChannels();
}
public List<ResolveInfo> getPackages() {
return packages;
}
public void setPackages(List<ResolveInfo> packages) {
this.packages = packages;
}
private void createNotificationChannels() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { //Check if device running Oreo or higher since notification channels only work Oreo or higher
NotificationChannel serviceChannel = new NotificationChannel(CHANNEL_ID , getString(R.string.service_channel_name) , NotificationManager.IMPORTANCE_LOW);
serviceChannel.setDescription(getString(R.string.service_channel_description)); // Can also change anything about channel, like its color
NotificationManager manager = getSystemService(NotificationManager.class);
if (manager != null)
manager.createNotificationChannel(serviceChannel);
}
}
And then I filled this packages
List inside the main activity like this:
final PackageManager pm = getPackageManager();
Intent main = new Intent(Intent.ACTION_MAIN, null);
main.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> packages = pm.queryIntentActivities(main, 0); //get a list of installed apps.
Notifications notifications = (Notifications) getApplicationContext();
notifications.setPackages(packages);
So then I can access this list from any other activity like so:
Notifications notifications = (Notifications) getApplicationContext();
List<ResolveInfo> packages = notifications.getPackages();
final PackageManager packageManager = getPackageManager();
final Drawable icon = packages.get(position).loadIcon(packageManager);
The problem is that there is a consensus that this is also a bad approach, that creating Application level Lists causes memory leaks. Is it a better or worse approach than using Intent? And what other method is there?