android handler 学习

本文通过一个具体的Android应用示例,展示了如何使用Handler在主线程与子线程间传递消息,实现UI更新。文章详细解释了Handler、Looper及Message的使用方法,并通过实例代码演示了线程间通信的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


package pos.app;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;

public class Android extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);

Button helpButton =(Button) findViewById(R.id.login_help);


helpButton.setOnClickListener(new Button.OnClickListener(){

@Override
public void onClick(View v) {

Intent intent = new Intent(AndroidApp.this,MyHandlerActivity.class);
startActivity(intent);
}

});
}
}




package pos.app;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.Button;

public class MyHandlerActivity extends Activity {

Button button;
MyHandler myHandler;

public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);

setContentView(R.layout.home);
setTitle("My Handler Activity");
button = (Button)findViewById(R.id.login_help);

myHandler = new MyHandler();

MyThread m = new MyThread();
new Thread(m).start();
}


class MyHandler extends Handler {

public MyHandler(){

}

public MyHandler( Looper L){
super(L);
}

@Override
public void handleMessage(Message msg){
Log.v("MyHandler", "handleMessage....");
super.handleMessage(msg);
Bundle bundle = msg.getData();
String text = bundle.getString("text");
MyHandlerActivity.this.button.setText(text);

}
}

class MyThread implements Runnable {

@Override
public void run() {

try{
Thread.sleep(1000);
}catch(Exception e){

}

Message msg = new Message();
Bundle bundle = new Bundle();
bundle.putString("text", "handler text");
msg.setData(bundle);

MyHandlerActivity.this.myHandler.sendMessage(msg);
}


}

}

[code="java"][/code]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值