Android 5.0.2使用AsyncTask发现内存不足错误

问题描述:

在我的Android应用程序中,我有一张使用AsyncTask填充的表格(在现实生活中,它所做的不仅仅是几个文本视图,但可以看到问题这种减少的代码以及):Android 5.0.2使用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); 
    } 
} 

此代码的工作完美我的三星Galaxy SIII手机上的Android 4.4,但在我的新的三星Galaxy S6边缘与Android 5.0.2之后我产生了内存不足的错误旋转设备3-4次(我可以旋转我的SIII几十次没有问题)。当我在SIII上运行时观看内存监视器时 - 我的内存始终保持在64MB以下,但是S6 Edge ... - 它始于64Mb,每次旋转设备时它都会增加大约30-40Mb,并且永远不会下降。我不知道我在这里错过了什么。

+0

你为什么要更新'doInBackground'中的UI? –

+0

不仅仅是为什么。因为这会立即崩溃应用程序。 – greenapps

+0

实际上,当这个AsyncTask运行的时候,这行并不是UI的一部分,应用程序根本没有崩溃(它正在被创建,并且会被添加到onPostExecute方法的表中。正如我刚才提到的,这只是整个事物的一个片段)。唯一的问题是,在更新的手机内存永远不会释放,并最终导致内存错误。 – RedSparkle

我猜,我知道我的问题的答案。我使用Android 5在不同设备上测试了我的应用程序,其中一些可以正常工作,而其他一些则很快就会出现OutOfMemory错误。我已经将我的代码从使用AsyncTasks切换到使用Runnable - 并且一切恢复正常。没有更多的内存错误,runnable可以完成它的工作并释放内存。