android如何阻塞主线程,Android-Android如何避免阻塞主线程
Android的Handler和AsyncTask,可以避免阻塞主線程(UI線程),且UI的更新只能在主線程中完成,因此異步處理是不可避免的。
AsyncTask,它使創建需要與用戶界面交互的長時間運行的任務變得更簡單。不需要借助線程和Handler即可實現。
獲取網頁的例子:
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.os.AsyncTask;
//設置三種類型參數分別為String,Integer,String
class PageTask extends AsyncTask {
// 可變長的輸入參數,與AsyncTask.exucute()對應
protected String doInBackground(String... params) {
try {
HttpClient client = new DefaultHttpClient();
// params[0] 代表連接的url
HttpGet get = new HttpGet(params[0]);
HttpResponse response = client.execute(get);
HttpEntity entity = response.getEntity();
long length = entity.getContentLength();
InputStream is = entity.getContent();
String s = null;
if (is != null) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[128];
int ch = -1;
int count = 0;
while ((ch = is.read(buf)) != -1) {
baos.write(buf, 0, ch);
count += ch;
if (length > 0) {
// 如果知道響應的長度,調用publishProgress()更新進度
publishProgress((int) ((count / (float) length) * 100));
}
// 為了在模擬器中清楚地看到進度,讓線程休眠100ms
Thread.sleep(100);
}
s = new String(baos.toByteArray());
}
// 返回結果
return s;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onCancelled() {
super.onCancelled();
}
protected void onPostExecute(String result) {
// 返回HTML頁面的內容
message.setText(result);
}
protected void onPreExecute() {
// 任務啟動,可以在這里顯示一個對話框,這里簡單處理
message.setText(R.string.task_started);
}
protected void onProgressUpdate(Integer... values) {
// 更新進度
message.setText(values[0]);
}
}
總結
以上是生活随笔為你收集整理的android如何阻塞主线程,Android-Android如何避免阻塞主线程的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 常用idea快捷键
- 下一篇: android 开发art,Androi