当我的应用程序第一次启动时,它应该显示用户协议,这是一个59kb的txt文件。由于它需要一些时间来读取文件并将其附加到文本视图,我决定在Async任务中执行该操作并显示进度条,但是进度条会冻结,直到文件被附加到文本视图,当发生这种情况时,应用程序需要一些时间来响应,有时会导致ANR。这是我的异步任务代码:
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 :(得分:3)
首先,您可以使用onProgressUpdate
更新进度条。
为了避免你的ANR我怀疑Html.fromHtml是一个阻止你的UI线程的昂贵的调用。您可以在doInBackground方法中返回Html值,并避免UI阻塞。