在我的Android应用程序中,我有一个使用AsyncTask填充的表格(在现实生活中,它只是做了很多文本视图,但是这个简化代码也可以看到问题):
private class RowPainter extends AsyncTask<Statistics, Void, Void>
{
private final WeakReference<TableRow> rowReference;
public RowPainter(TableRow row)
{
rowReference = new WeakReference<>(row);
}
@Override
protected Void doInBackground(Statistics... statistics)
{
fillDetailsRow(statistics[0]);
return null;
}
@Override
protected void onPostExecute(Void aVoid)
{
rowReference.clear();
}
private void fillDetailsRow(Statistics stats)
{
fillText(R.id.name, stats.name, rowReference);
fillText(R.id.level, printableValue(stats.level), rowReference);
fillText(R.id.total_count, printableValue(stats.TotalCount), rowReference);
fillText(R.id.track_score, printableValue(stats.calculateScore()), rowReference);
}
private void fillText(int viewId, String text, WeakReference<TableRow> reference)
{
TableRow row = reference.get();
if (row == null)
return;
TextView textView = (TextView) row.findViewById(viewId);
textView.setText(text);
}
private String printableValue(int value)
{
return value == 0 ? "" : String.format("%,d", value);
}
}
这个代码适用于我的带有Android 4.4的三星Galaxy SIII手机,但在我的新款三星Galaxy S6 Edge和Android 5.0.2上,我旋转设备3-4次后会产生内存错误(我可以旋转我的SIII)几十次没有问题)。当我在SIII上运行时在Android Studio中观看内存监视器 - 我的内存始终保持在64MB以下,但S6 Edge ... - 它从64Mb开始,每次我旋转设备时它增加了大约30-40Mb并且永远不会下降。我不确定我在这里错过了什么。
答案 0 :(得分:0)
我想,我知道我的问题的答案。我在Android 5的不同设备上测试了我的应用程序,其中一些工作正常,而其他人很快就会出现OutOfMemory错误。我已经将我的代码从使用AsyncTasks转换为使用Runnable - 一切都恢复正常。没有更奇怪的内存错误,runnable可以完成它的工作并释放内存就像它应该的那样。