我遇到内存泄漏问题。我从http(800KB)下载图像并使用AsyncTask将其存储在Drawable中。下载图像后,内存似乎没问题。但是,在将Drawable设置为RelativeLayout的背景图像后,内存大小增加大约8-10 MEGABYTES。我使用getUsedMem()来跟踪内存使用情况。如果我使用其中的几个,Android应用程序崩溃与OutOfMemoryException。有谁知道这个问题?如何在此处最小化内存使用量?
public class Example extends Activity {
private ArrayList<Drawable> drawables;
private TextView tv;
private RelativeLayout rl1;
@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
drawables = new ArrayList<Drawable>();
tv = (TextView) findViewById(R.id.textView1);
rl1 = new RelativeLayout(this);
// Check Memory Before Everything
printMemory(0);
// Image url
String image_url1 = "https://s3-us-west-1.amazonaws.com/example/image.jpg";
new DownloadFilesTask().execute(image_url1);
}
public Drawable drawableFromUrl(String url, String srcName) throws java.net.MalformedURLException, java.io.IOException {
InputStream is = (InputStream) new java.net.URL(url).getContent();
Drawable drawable = Drawable.createFromStream(is, srcName);
is.close();
return drawable;
}
@SuppressLint("NewApi")
public void addDrawable(Drawable d) {
drawables.add(d);
rl1.setBackground(d);
printMemory();
}
private class DownloadFilesTask extends AsyncTask<String, Drawable, Drawable> {
protected Drawable doInBackground(String... s)
{
Drawable bgImage = Example.this.drawableFromUrl(s[0], "src name");
return bgImage;
}
protected void onPostExecute(Drawable drawable) {
addDrawable(drawable);
}
}
public long getUsedMem() {
long freeSize = 0L;
long totalSize = 0L;
long usedSize = -1L;
try {
Runtime info = Runtime.getRuntime();
freeSize = info.freeMemory();
totalSize = info.totalMemory();
usedSize = totalSize - freeSize;
} catch (Exception e) {
e.printStackTrace();
}
return usedSize;
}
public long getTotalMem() {
long totalSize = 0L;
try {
Runtime info = Runtime.getRuntime();
totalSize = info.totalMemory();
} catch (Exception e) {
e.printStackTrace();
}
return totalSize;
}
public void printMemory() {
CharSequence cs = tv.getText();
tv.setText(cs + "\n" +
"Used Mem: " + getUsedMem() + "\n" +
"Total Mem: " + getTotalMem() + "\n" +
"Drawables: " + drawables.size());
}
}