咱們在使用手機的時候,常常會遇到一個問題:先是卡死,而後跳出該程序無響應,是否關閉的提示(固然有多是咱們手機性能太差=。=)這是由於線程的阻塞引發的,在這裏我講述一下UI線程,通常處理程序會在UI線程中執行耗時操做,這回致使UI線程阻塞,當UI線程阻塞,屏幕會出現卡死,用戶體驗會變得很是差,當線程阻塞超過5s,android系統可能進行干預,彈出對話框詢問是否關閉。那如何解決呢?android
解決方案一:建立一個新線程app
我在UI視圖中建立了一個button和一個textViewide
Button button=(Button)findViewById (R.id.button);
TextView textView=(TextView)findViewById(R.id.textView); TranslateAnimation animation=new TranslateAnimation(0,200,0,0); animation.setRepeatCount(3); animation.setDuration(2000); textView.setAnimation(animation); //這裏我讓textView在進入app時進行移動動畫 button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View v) {//監聽button的點擊 new Thread(new Runnable() {//建立一個新線程 @Override public void run() { try { Thread.sleep(5000);//在這裏我讓線程進行耗時操做 } catch (InterruptedException e){
e.printStackTrace();
} } }).start(); }
});
上面的代碼我建立一個新的線程來實現耗時,可是實際過程當中進行的不可能只是一個耗時操做,讓咱們在新線程中加兩句話,TextView view=(TextView)v;view.setText(""+100);(獲取到當前控件,並將其文字設置成100)如今讓咱們再來試試這個程序,這個時候程序又報錯了post
Only the original thread that created a view hierarchy can touch its views.
翻譯成中文就是:只有建立view的那個線程才能對其進行修改。性能
其實谷歌有兩條建議,也能夠說是規矩動畫
there are simply two rules to Android's single thread model:
Do not block the Ui thread//不要阻塞UI線程
Do not access the Android UI toolkit from outside the UI thread//不要在UI線程外的其餘線程對視圖中的組件進行設置
那麼不少人就有疑問了,這不是矛盾了嗎?谷歌也爲咱們提供瞭解決方案url
解決方案一:view.postspa
上面代碼出錯是由於咱們在UI以外的線程調用了UI控件;那麼如今,咱們在try{}catch(){}語句後增長一下代碼線程
1 v.post(new Runnable() { 2 @Override 3 public void run() { 4 TextView view=(TextView)v; 5 view.setText(""+sun); 6 } 7 });
這段代碼將個人語句提交到了UI線程中;可是view.post也有一些缺點翻譯
冗餘,可讀性差,維護性差
爲此官方也提供了另一種解決方法
解決方法二:AsyncTask
AsyncTask和post方法大同小異
private class DownloadImageTask extends AsyncTask<String ,Void,Integer>{ protected Integer doInBackground(String...urls){ try{ Thread.sleep(5000); }catch (InterruptedException e){ e.printStackTrace(); } int sun=100; return sun; } protected void onPostExecute(Integer sum){ button2.setText(""+sum); } }
button2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new DownloadImageTask().execute(); } });
咱們如今外部建立一個方法,而後在button的onClick事件中引用。