【发布时间】:2014-04-13 08:31:59
【问题描述】:
我有以下类,我尝试将其实现为 Parcelable 类。 问题是这个类需要一个上下文,所以我不能让它成为 Parcelable。 我需要能够跨不同活动访问该类的对象,以便共享应用程序使用的位图。一些相同的位图在整个应用程序中使用。
我遇到了内存不足的问题,因此我正在尝试将其用作解决方案。
public class ImageManager implements Parcelable {
private static final long serialVersionUID = 66;
private HashMap<Integer, Bitmap> mBitmaps;
private HashMap<Integer, Drawable> mDrawables;
private Context mContext;
private boolean mActive = true;
public ImageManager(Context c) {
mBitmaps = new HashMap<Integer, Bitmap>();
mDrawables = new HashMap<Integer, Drawable>();
mContext = c;
}
public ImageManager(Parcel in) {
// TODO Auto-generated constructor stub
}
// We need to share and cache resources between objects to save on memory.
public Bitmap getBitmap(int resource) {
if (mActive) {
if (!mBitmaps.containsKey(resource)) {
mBitmaps.put(resource,
BitmapFactory.decodeResource(mContext.getResources(), resource));
}
return mBitmaps.get(resource);
}
return null;
}
public Drawable getDrawable(int resource) {
if (mActive) {
if (!mDrawables.containsKey(resource)) {
mDrawables.put(resource, mContext.getResources().getDrawable(resource));
}
return mDrawables.get(resource);
}
return null;
}
public void recycleBitmaps() {
Iterator itr = mBitmaps.entrySet().iterator();
while (itr.hasNext()) {
Map.Entry e = (Map.Entry)itr.next();
((Bitmap) e.getValue()).recycle();
}
mBitmaps.clear();
}
public ImageManager setActive(boolean b) {
mActive = b;
return this;
}
public boolean isActive() {
return mActive;
}
@Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
// TODO Auto-generated method stub
dest.writeValue(mBitmaps);
dest.writeValue(mDrawables);
//dest.writeValue(mContext);
dest.writeByte((byte) (mActive ? 0x01 : 0x00));
}
public static final Parcelable.Creator<ImageManager> CREATOR = new Parcelable.Creator<ImageManager>() {
public ImageManager createFromParcel(Parcel in) {
return new ImageManager(in);
}
public ImageManager[] newArray(int size) {
return new ImageManager[size];
}
};
}
【问题讨论】:
-
那么上面的代码有什么问题
-
我需要能够通过整个应用程序,通过不同的活动来访问同一个对象。目前我正在为每个活动创建一个新对象,以便能够使用该类。
-
创建静态对象并在整个应用程序中使用它..
标签: java android memory-management