2013-08-05 62 views
0

當我的應用程序第一次啓動時,它應該顯示用戶協議,它是一個59kb的txt文件。由於它需要一些時間來讀取文件並將其附加到文本視圖,我決定在異步任務中對其進行處理,並在顯示進度條的同時顯示進度條,但進度條會凍結,直到文件被附加到文本視圖,當發生這種情況時,應用程序需要一些時間才能響應,有時會導致ANR。這裏是我的異步任務代碼:在AsyncTask期間UI凍結

public class DownloadFilesTask extends AsyncTask<String, Integer, String> { 

    AlertDialog alertDialog = null; 
    Button getstarted, cancel; 
     TextView text2; 
     AlertDialog.Builder builder; 
     LayoutInflater inflater = (LayoutInflater) Profile.this.getSystemService(LAYOUT_INFLATER_SERVICE); 
     View layout = inflater.inflate(R.layout.agreement, (ViewGroup) findViewById(R.id.layout_root)); 

protected void onPreExecute(){ 
    progressDialog = ProgressDialog.show(Profile.this, "", "Loading.....", true); 
     getstarted=(Button) layout.findViewById(R.id.get_started); 
     cancel=(Button) layout.findViewById(R.id.cancel); 

     cancel.setVisibility(View.GONE); 
     text2 = (TextView) layout.findViewById(R.id.ag); 

     builder = new Builder(Profile.this); 
     builder.setView(layout); 
     alertDialog = builder.create(); 
     alertDialog.setCancelable(false); 
     alertDialog.setTitle(getString(R.string.terms)); 
    } 

@Override 
protected String doInBackground(String... arg0) { 
    StringBuilder sb = new StringBuilder(); 
try { 
     AssetManager am = getAssets(); 
     InputStream in = am.open("EULA.txt"); 
     BufferedReader reader = new BufferedReader(new InputStreamReader(in)); 

      String line = null; 

      while ((line = reader.readLine()) != null) { 
       sb.append(line); 
      } 

      in.close(); 


    } catch(Exception e){ 

      System.out.println("FILE NOT FOUND : "+ e.getMessage()); 
    } 

     return sb.toString(); 
     } 
// This is called when doInBackground() is finished 
    protected void onPostExecute(String result) { 
     progressDialog.dismiss(); 
     alertDialog.show(); 
     text2.setText(Html.fromHtml(result)); 

     } 

     // This is called each time you call publishProgress() 
} 

正如你可以看到我的文件追加到postExecute方法文本視圖。我應該改變閱讀文件的方式嗎?或者是別的什麼。在此先感謝

+0

你是如何調用'AsyncTask'? – codeMagic

+0

我知道,但老闆希望達成協議,因爲客戶以前遇到過問題。相信我,我建議儘量縮短,但不要運氣。 – wnieves19

回答

3

首先,您可以使用onProgressUpdate更新進度欄。

爲了避免你的ANR,我懷疑Html.fromHtml是一個阻止你的UI線程的昂貴調用。您可以在doInBackground方法中返回Html值並避免UI阻塞。

example of use onProgressUpdate to update the progress bar

+0

您好我有Html.fromHtml,因爲它之前是一個html文件,但隨後我將它移動到一個txt文件,因爲它更小。我刪除它,但沒有運氣 – wnieves19

+0

也許你可以使用webview而不是textview,也可以使用assets文件夾來存儲html頁面。就像在這個問題: http://stackoverflow.com/questions/8737488/problems-loading-html-asset-into-webview/8737547#8737547 –

+0

嗯有趣,我會盡力並回復你 – wnieves19