當我的應用程序第一次啓動時,它應該顯示用戶協議,它是一個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方法文本視圖。我應該改變閱讀文件的方式嗎?或者是別的什麼。在此先感謝
你是如何調用'AsyncTask'? – codeMagic
我知道,但老闆希望達成協議,因爲客戶以前遇到過問題。相信我,我建議儘量縮短,但不要運氣。 – wnieves19