Android学习篇章40-Handler多线程基础

来源:互联网 发布:java视频教程2016 编辑:程序博客网 时间:2024/06/08 08:15

Mainactivity:

public class MainActivity extends Activity {TextView  prcTxt=null;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);prcTxt=(TextView)findViewById(R.id.prcTxt);}//使用自定义Handlerpublic void clickBtn(View view){new Thread(){public void run(){int i=0;    while(i<=100)    {    SystemClock.sleep(100);    i++;    //在子线程中将当前进度通过Handler发送给主线程                    Message msg=handler.obtainMessage();                    Bundle data=new Bundle();                    data.putInt("progress", i);                    msg.setData(data);                    msg.what=0x201;    handler.sendMessage(msg);    }}}.start();}//当把handler创建出来后 这个handler就与主线程绑定//同时也与这个主线程的Looper和Looper所管理的消息队列//MessageQueue绑定  Handler h2=new Handler();//这两个Handler所能处理的消息队列不是同一个     Handler handler=new Handler(){     //这个方法 接收Looper从消息队列中取出的Message 进行处理@Overridepublic void handleMessage(Message msg) {               //一般来说消息队列中的消息会有很多类型,所以先要区分不同的消息   //可以通过what属性进行  if(msg.what==0x201)  {                   Bundle data= msg.getData();                   int progress=data.getInt("progress");                   prcTxt.setText(""+progress+"%");  }}               };//使用View.post方式public void clickBtn2(View view){new Thread(){int i=0;public  void run(){while(i<100){  SystemClock.sleep(500);  i++;  prcTxt.post(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stub   prcTxt.setText(""+i+"%");}     });}}}.start();}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}}

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"    tools:context=".MainActivity" >    <TextView android:id="@+id/prcTxt"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:textSize="35sp"        android:textColor="#f00"        android:text="" />    <Button android:id="@+id/btn1"        android:onClick="clickBtn"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="开始下载" /></LinearLayout>


原创粉丝点击