知識(shí)
不管是網(wǎng)站,軟件還是小程序,都要直接或間接能為您產(chǎn)生價(jià)值,我們?cè)谧非笃湟曈X表現(xiàn)的同時(shí),更側(cè)重于功能的便捷,營(yíng)銷的便利,運(yùn)營(yíng)的高效,讓網(wǎng)站成為營(yíng)銷工具,讓軟件能切實(shí)提升企業(yè)內(nèi)部管理水平和效率。優(yōu)秀的程序?yàn)楹笃谏?jí)提供便捷的支持!
AndroidHandler詳細(xì)介紹+示例
發(fā)表時(shí)間:2021-1-4
發(fā)布人:葵宇科技
瀏覽次數(shù):38
本文主要介紹Android中Handler的使用方法,Handler跟多線程,消息隊(duì)列聯(lián)系很緊密,在平常的實(shí)際程序開發(fā)中比較常見。本文分為4個(gè)簡(jiǎn)單的例子。
Handler使用例1
這個(gè)例子是最簡(jiǎn)單的介紹handler使用的,是將handler綁定到它所建立的線程中.
本次實(shí)驗(yàn)完成的功能是:單擊Start按鈕,程序會(huì)開始啟動(dòng)線程,并且線程程序完成后延時(shí)1s會(huì)繼續(xù)啟動(dòng)該線程,每次線程的run函數(shù)中完成對(duì)界面輸出nUpdateThread...文字,不停的運(yùn)行下去,當(dāng)單擊End按鈕時(shí),該線程就會(huì)停止,如果繼續(xù)單擊Start,則文字又開始輸出了。代碼如下:
MainActivity.java
package com.example.handler1; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; public class MainActivity extends Activity { private TextView text_view = null; private Button start = null; private Button end = null; //使用handler時(shí)首先要?jiǎng)?chuàng)建一個(gè)handler Handler handler = new Handler(); //要用handler來處理多線程可以使用runnable接口,這里先定義該接口 //線程中運(yùn)行該接口的run函數(shù) Runnable update_thread = new Runnable() { public void run() { //線程每次執(zhí)行時(shí)輸出"UpdateThread..."文字,且自動(dòng)換行 //textview的append功能和Qt中的append類似,不會(huì)覆蓋前面 //的內(nèi)容,只是Qt中的append默認(rèn)是自動(dòng)換行模式 text_view.append("\nUpdateThread..."); //延時(shí)1s后又將線程加入到線程隊(duì)列中 handler.postDelayed(update_thread, 1000); } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); text_view = (TextView)findViewById(R.id.text_view); start = (Button)findViewById(R.id.start); start.setOnClickListener(new StartClickListener()); end = (Button)findViewById(R.id.end); end.setOnClickListener(new EndClickListener()); } private class StartClickListener implements OnClickListener { public void onClick(View v) { // TODO Auto-generated method stub //將線程接口立刻送到線程隊(duì)列中 handler.post(update_thread); } } private class EndClickListener implements OnClickListener { public void onClick(View v) { // TODO Auto-generated method stub //將接口從線程隊(duì)列中移除 handler.removeCallbacks(update_thread); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } }activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:id="@+id/text_view" android:layout_width="fill_parent" android:layout_height="200dip" android:text="@string/hello_world" tools:context=".MainActivity" /> <Button android:id="@+id/start" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/start" /> <Button android:id="@+id/end" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/end" /> </LinearLayout>
Handler使用例2
這個(gè)例子比剛才那個(gè)例子稍微復(fù)雜些。因?yàn)檫@個(gè)例子中用到了handler的消息隊(duì)列機(jī)制,即通過handler中一個(gè)線程向消息隊(duì)列中用sendMessage方法發(fā)送消息,發(fā)送的消息當(dāng)然可以用來傳遞參數(shù)。在handler中用handleMessage來處理消息,處理方法是獲得消息隊(duì)列中的消息參數(shù),用這些參數(shù)來完成另外一些功能。
本實(shí)驗(yàn)實(shí)現(xiàn)的是當(dāng)開始按鈕按下時(shí),會(huì)啟動(dòng)一個(gè)線程,并綁定到handler中,該線程發(fā)送帶有參數(shù)的message到handler的消息隊(duì)列中,消息隊(duì)列的另一端獲取該消息,并且用該消息的參數(shù)來更新進(jìn)度條。
MainActivity.java
package com.example.handler2; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ProgressBar; public class MainActivity extends Activity { private ProgressBar progress_bar = null; private Button start = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); progress_bar = (ProgressBar)findViewById(R.id.progress_bar); start = (Button)findViewById(R.id.start); start.setOnClickListener(new StartOnClickListenr()); } private class StartOnClickListenr implements OnClickListener { public void onClick(View v) { // TODO Auto-generated method stub //讓進(jìn)度條顯示出來 progress_bar.setVisibility(View.VISIBLE); //將線程加入到handler的線程隊(duì)列中 update_progress_bar.post(update_thread); } } //創(chuàng)建一個(gè)handler,內(nèi)部完成處理消息方法 Handler update_progress_bar = new Handler() { @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub //super.handleMessage(msg); //顯示進(jìn)度條 progress_bar.setProgress(msg.arg1); //重新把進(jìn)程加入到進(jìn)程隊(duì)列中 update_progress_bar.post(update_thread); } };//不加這個(gè)分號(hào)則不能自動(dòng)添加代碼 Runnable update_thread = new Runnable() { int i = 0; public void run() { // TODO Auto-generated method stub i += 10; //首先獲得一個(gè)消息結(jié)構(gòu) Message msg = update_progress_bar.obtainMessage(); //給消息結(jié)構(gòu)的arg1參數(shù)賦值 msg.arg1 = i; //延時(shí)1s,java中的try+catch用來排錯(cuò)處理 try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO: handle exception e.printStackTrace(); } //把消息發(fā)送到消息隊(duì)列中 update_progress_bar.sendMessage(msg); if(i == 100) //把線程從線程隊(duì)列中移除 update_progress_bar.removeCallbacks(update_thread); } }; @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } }
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" > <Button android:id="@+id/start" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:text="@string/start" /> <ProgressBar android:id="@+id/progress_bar" android:layout_width="fill_parent" android:layout_height="100dip" android:layout_alignParentTop="true" style="?android:attr/progressBarStyleHorizontal" android:visibility="gone" /> </RelativeLayout>
Handler使用例3
上面2個(gè)例子表面上看handler使用了post方法啟動(dòng)了runnbale,其實(shí)啟動(dòng)的線程和activity主線程是同一個(gè)線程,因?yàn)樗皇沁\(yùn)行了線程的run方法,而不是start方法。Mars老師實(shí)驗(yàn)3的目的是為了驗(yàn)證僅使用handler的post方法是否處于同一個(gè)線程。
該實(shí)驗(yàn)在主activtiy的onCreate函數(shù)中打印了2條關(guān)于本線程的信息,然后創(chuàng)建一個(gè)handler并為它綁定一個(gè)線程,在線程的run方法中也打印了線程的信息,觀察2者的信息是否一樣。
結(jié)果如下:
說明這2個(gè)線程確實(shí)是同一線程,并且可以看出主界面中的文字大概過了10s才顯示出來,因?yàn)檎Z句setContentView(R.layout.activity_main);放在了handler的post啟動(dòng)語句后面,而handler綁定的線程中又延時(shí)了10s,所以同時(shí)也證明了只有是同一個(gè)線程才會(huì)出現(xiàn)這種情況。
程序主要代碼和注釋如下:
MainActivity.java
package com.example.handler3; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.view.Menu; public class MainActivity extends Activity { //新建一個(gè)handler private Handler handler = new Handler(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //將runnable加載到handler的線程隊(duì)列中去 // handler.post(r); Thread t = new Thread(r); t.start(); setContentView(R.layout.activity_main); //打印activtiy線程信息 System.out.println("activity_id---->"+Thread.currentThread().getId()); System.out.println("activity_name---->"+Thread.currentThread().getName()); } Runnable r = new Runnable() { public void run() { // TODO Auto-generated method stub //打印新建線程信息 System.out.println("handler_id---->"+Thread.currentThread().getId()); System.out.println("handler_name---->"+Thread.currentThread().getName()); //延時(shí)10s,為了觀察主界面中內(nèi)容出現(xiàn)的時(shí)間 try { Thread.sleep(10000); } catch (InterruptedException e) { // TODO: handle exception e.printStackTrace(); } } }; @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } }
如果把語句:
handler.post(r);
換成:
Thread t = new Thread(r);
t.start();
其它的不變,則程序運(yùn)行時(shí)主界面內(nèi)容立刻就顯示出來了,且系統(tǒng)輸出如下:
這2者都說明這樣綁定的線程與它所在的activity線程就不是同一個(gè)線程了。
Handler使用例4
這個(gè)例子將學(xué)會(huì)怎樣不使用runnable來啟動(dòng)一個(gè)線程,而是用HandlerThread的looper來構(gòu)造一個(gè)handler,然后該handler自己獲得消息,并傳遞數(shù)據(jù),然后又自己處理消息,當(dāng)然這是在另一個(gè)線程中完成的。
消息結(jié)構(gòu)中傳遞簡(jiǎn)單的整型可以采用它的參數(shù)arg1和arg2,或者傳遞一些小的其它數(shù)據(jù),可以用它的object,該object可以是任意的對(duì)象。當(dāng)需要傳送比較大的數(shù)據(jù)是,可以使用消息的setData方法,該方法需要傳遞一個(gè)Bundle的參數(shù)。Bundle中存放的是鍵值對(duì)的map,只是它的鍵值類型和數(shù)據(jù)類型比較固定而已。
程序主要代碼和注釋如下:
MainActivity.java
package com.example.handler4; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.HandlerThread; import android.os.Looper; import android.os.Message; import android.view.Menu; public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); System.out.println("activity_ID---->"+Thread.currentThread().getId()); //新建一個(gè)HanderThread對(duì)象,該對(duì)象實(shí)現(xiàn)了用Looper來處理消息隊(duì)列的功能 HandlerThread handler_thread = new HandlerThread("handler_thread"); handler_thread.start(); //MyHandler類是自己繼承的一個(gè)類,這里采用hand_thread的Looper來初始化它 MyHandler my_handler = new MyHandler(handler_thread.getLooper()); //獲得一個(gè)消息msg Message msg = my_handler.obtainMessage(); //采用Bundle保存數(shù)據(jù),Bundle中存放的是鍵值對(duì)的map,只是它的鍵值類型和數(shù)據(jù)類型比較固定而已 Bundle b = new Bundle(); b.putString("whether", "晴天"); b.putInt("temperature", 34); msg.setData(b); //將msg發(fā)送到自己的handler中,這里指的是my_handler,調(diào)用該handler的HandleMessage方法來處理該mug msg.sendToTarget(); } class MyHandler extends Handler { //空的構(gòu)造函數(shù) public MyHandler() {} //以Looper類型參數(shù)傳遞的函數(shù),Looper為消息泵,不斷循環(huán)的從消息隊(duì)列中得到消息并處理,因此 //每個(gè)消息隊(duì)列都有一個(gè)Looper,因?yàn)長(zhǎng)ooper是已經(jīng)封裝好了的消息隊(duì)列和消息循環(huán)的類 public MyHandler(Looper looper) { //調(diào)用父類的構(gòu)造函數(shù) super(looper); } @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub System.out.println("Handler_ID---->"+Thread.currentThread().getId()); System.out.println("Handler_Name---->"+Thread.currentThread().getId()); //將消息中的bundle數(shù)據(jù)取出來 Bundle b = msg.getData(); String whether = b.getString("whether"); int temperature = b.getInt("temperature"); System.out.println("whether= "+whether+" ,temperature= "+temperature); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } }
總結(jié):
Android中的handler可以用來完成異步的消息出來,即發(fā)送消息和接收消息相互獨(dú)立,可以同時(shí)運(yùn)行。在例1和例2中,實(shí)際上handler中使用的線程是與它所在的activity處于同一個(gè)主線程,因?yàn)閔andler中調(diào)用的runnable接口是直接運(yùn)行該接口的run函數(shù)的,而不是start函數(shù)。例3專門比較了這2中情況。例4學(xué)會(huì)使用怎樣在新線程中處理消息的方法。
相關(guān)案例查看更多
相關(guān)閱讀
- 網(wǎng)站建設(shè)價(jià)格
- 網(wǎng)站小程序
- 昆明網(wǎng)絡(luò)公司
- 大理小程序開發(fā)
- 開通微信小程序被騙
- 區(qū)塊鏈
- 小程序開發(fā)排名前十名
- 云南軟件公司
- 云南小程序開發(fā)公司
- 百度推廣
- 云南建設(shè)廳網(wǎng)站
- 人口普查小程序
- 小程序開發(fā)費(fèi)用
- 云南網(wǎng)站建設(shè)專業(yè)品牌
- 政府網(wǎng)站建設(shè)服務(wù)
- 小程序密鑰
- 百度小程序
- 昆明小程序開發(fā)
- 云南做軟件
- 網(wǎng)站建設(shè)哪家強(qiáng)
- 云南小程序被騙
- 網(wǎng)站建設(shè)服務(wù)
- 報(bào)廢車回收管理系統(tǒng)
- 小程序商城
- 云南小程序開發(fā)推薦
- 智慧農(nóng)貿(mào)市場(chǎng)
- web教程
- 云南網(wǎng)站建設(shè)特性
- 網(wǎng)站建設(shè)公司哪家好
- 云南網(wǎng)站建設(shè) 網(wǎng)絡(luò)服務(wù)