2015-07-12 21 views
0

在我的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

回答

0

我猜,我知道我的問題的答案。我使用Android 5在不同設備上測試了我的應用程序,其中一些可以正常工作,而其他一些則很快就會出現OutOfMemory錯誤。我已經將我的代碼從使用AsyncTasks切換到使用Runnable - 並且一切恢復正常。沒有更多的內存錯誤,runnable可以完成它的工作並釋放內存。