问题
Here is the code : (All executed async while showing a progress bar)
List<ResolveInfo> apps = pm.queryIntentActivities(intent, PackageManager.GET_META_DATA);
for (ResolveInfo app : apps) {
String label = app.activityInfo.loadLabel(pm).toString();
Drawable icon = app.activityInfo.loadIcon(pm);
Drawable resizedIcon = null;
if (icon instanceof BitmapDrawable) {
resizedIcon = Graphics.resize(icon, res, iconW, iconH);
}
AppInfo ai = new AppInfo(app, label, resizedIcon);
items.add(ai);
}
Here is Graphics.resize()
:
Bitmap b = ((BitmapDrawable)image).getBitmap();
Bitmap bitmapResized = Bitmap.createScaledBitmap(b, widthPx, heightPx, false);
b.recycle();
return new BitmapDrawable(res, bitmapResized);
Generally it all works fine, but I did get a report about out of memory exception while calling Bitmap.createScaledBitmap
(i'm trying to re-size to 32dp)
I read about handling and displaying bitmaps , but here, I want the app icon to be displayed immediately while the user sees the app name, and not just start being loaded. (which I can achieve by using RecyclerView
)
回答1:
when system can't satisfy needs of application specially resource you will get this error as you can see this is happening as you are running low on memory
you ca increase the amount of heap memory provided to your application (process
) by adding an attribute
to the application tag in the AndroidManifest.xml
which is
android:largeHeap="true"
your application tag would look something like this...
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:largeHeap="true"
android:theme="@style/AppTheme">
Although it will increase the memory provided to the application (process
). it does not guarantee that it would be enough for the task you want to perform.
if you are trying to start a memory expensive Task
, add this like of code
System.gc();
This may free up some memory for you on the heap. but it completely depends on DVM ( Dalivik Virtual Machine)
to deal with heap
.
Make sure you call this before starting your heavy task
otherwise it would be useless calling it after the Task has been completed.
if you are facing this issue on emulator
you can try increasing the heap memory of the AVD (Android Virtual Device)
like this
When dealing with bitmaps images try to get them in as small as possible they are the common culprit for OutOfMemory
error.
回答2:
You can set the large heap attribute to true.
There is also a way you can use image loader in that image so the icon you get will be stored on the device.
来源:https://stackoverflow.com/questions/34661257/load-applications-icons-and-getting-outofmemory-exception-while-resizing