android之Handler,activity,service總結

來源:互聯網
上載者:User

1、Handler學習

由於有時要進行哪些耗時操作,如果這些操作放在主線程的話,容易導致程式假死,最後結果是系統崩潰。因此要進行某些耗時操作時,將其放在子線程進行,這樣就涉及如何解決子線程與主線程之間通訊問題(訊息佇列)。

Handler就是為瞭解決這個問題而存在的。當你處理某個耗時操作時,你將其放在子線程,子線程處理完後,將其結果放在訊息佇列中,然後主線程從訊息佇列中讀取子線程處理結果,最後根據結果更新主線程。這樣就是Handler處理整個流程。

Handler主要有兩種方式實現主線程與子線程通訊:

一、通過post(Runnable對象)將Runnable對象加到訊息佇列中,然後主線程從訊息佇列中讀取Runnable對象,根據結果更新主線程。

package com.test.ui;import android.app.Activity;import android.os.Handler;import android.os.Bundle;import android.os.Message;import android.view.View;import android.widget.Button;import android.widget.ProgressBar;public class TestActivity extends Activity {    /** Called when the activity is first created. */     Button btn1,btn2;    ProgressBar progress;    int tmp = 0;    Handler handler = new Handler();    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        btn1 = (Button)findViewById(R.id.button1);        btn2 = (Button)findViewById(R.id.button2);        progress = (ProgressBar)findViewById(R.id.progressBar1);                btn1.setOnClickListener(new View.OnClickListener() {  //button控制項事件監聽            @Override              public void onClick(View v) {              handler.post(update);  //通過post函數,將Runnable對象加到訊息佇列中,根據訊息結果更新progress            }          });          }        Runnable update = new Runnable() {  //建立子線程,專門處理耗時操作,然後在主線程更新progress。        @Override          public void run() {              if (progress.getProgress() < 100) {                  tmp += 10;                  progress.setProgress(tmp);                  progress.setSecondaryProgress(tmp + 10);                  handler.postDelayed(update, 800); //延時0.8秒後,將Runnable對象重新加到訊息佇列中             } else {                  handler.removeCallbacks(update); //從訊息撤銷Runnable對象                progress.setVisibility(View.GONE);  //progress不可見                tmp = 0;              }          }      };}

二、第二種Handler通訊辦法是,通過子線程sendMessage函數,將訊息發送到訊息佇列中。然後在主線程通過重寫handlerMessage讀取訊息佇列中Message,然後更新主線程。

      函數調用整個過程:

      通過post()將Runnable對象加到訊息佇列中,然後運行Runnable對象的run函數,通過sendMessage訊息,run函數運行完後,在主線程調用handlerMessage函數,更新UI,如果UI更新完成,通過removeCallB
acks將Runnable對象從隊列中撤銷。

package com.test.ui;import android.app.Activity;import android.os.Handler;import android.os.Bundle;import android.os.Message;import android.view.View;import android.widget.Button;import android.widget.ProgressBar;public class TestActivity extends Activity {        private Button btn1;    private ProgressBar progress;    int tmp = 0;        Handler handler = new Handler(){@Overridepublic void handleMessage(Message msg) {progress.setProgress(msg.arg1);if(msg.arg1 == 100){handler.removeCallbacks(update);//更新完成了,將Runnable對象撤銷      progress.setVisibility(View.GONE);      tmp = 0;}elsehandler.post(update);//更新沒完成,繼續將要執行的線程放入到隊列當中}    };        public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        btn1 = (Button)findViewById(R.id.button1);        progress = (ProgressBar)findViewById(R.id.progressBar1);                btn1.setOnClickListener(new View.OnClickListener(){//事件監聽         public void onClick(View v) {                      //設定進度條為可見狀態                      progress.setVisibility(View.VISIBLE);                      handler.post(update);            }          });    }                Runnable update = new Runnable() {  //建立子線程,專門處理耗時操作,然後在主線程更新progress。        public void run() {         tmp =tmp + 10;            Message msg = handler.obtainMessage();         msg.arg1 = tmp;        try{                      Thread.sleep(800); //讓當前線程休眠800毫秒                  }catch(InterruptedException ex){                      ex.printStackTrace();                  }                  handler.sendMessage(msg); //將訊息發送到訊息佇列中,等待主線程調用handlerMessage函數處理(run運行完後處理)                if(tmp == 100){        handler.removeCallbacks(update);//更新完成了,將Runnable對象撤銷        tmp = 0;        }        }      };   }

2、activity學習

3、service學習

4、Message學習

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.