2013-08-05 146 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