如图:
数字部分每隔2秒自加1,。。。。。。
逻辑代码文件:
<span style="font-size:18px;"><span style="font-size:18px;">package com.example.day18_handler;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
TextView tv;
int count=0;
//处理从工作线程发送过来的消息
Handler handler=new Handler(){
public void handleMessage(android.os.Message msg) {
int num=msg.arg1;
tv.setText(num+"");
//int a1=msg.arg1;
int a2=msg.arg2;
String a3=(String) msg.obj;
int a4=msg.what;
String a5=msg.getData().getString("str");
Toast.makeText(getApplicationContext(),
"整型:a2="+a2+"\n传过来的对象:a3="+a3+"\n标记:a4="+a4+"\nBundle对象数据:a5="+a5, 0).show();
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv=(TextView) findViewById(R.id.tv);
new Thread(){
public void run() {
while(true)
{
if(count<50)
{
count++;
}
//得到Message对象
//Message msg=Message.obtain();
Message msg=handler.obtainMessage();
msg.arg1=count;//将值封装到msg,携带过去
handler.sendMessage(msg);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
}.start();
}
public void click(View v)
{
new Thread(){
public void run() {
Message msg1=Message.obtain();
//msg1.arg1=100;
msg1.arg2=200;
msg1.obj="wwwdfr";
msg1.what=3;//标记
Bundle bundle=new Bundle();
bundle.putString("str", "大数据");
msg1.setData(bundle);
handler.sendMessage(msg1);
};
}.start();
}
}
</span></span>
布局文件:
<span style="font-size:18px;"><span style="font-size:18px;"><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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<Button
android:id="@+id/bt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="子线程向主线程发送消息"
android:onClick="click"
android:layout_below="@+id/tv"/>
</RelativeLayout>
</span></span>