package com.example.myhandlertest3; import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
/**
* Android Handler
* @author shaobn
* @date 2015/9/9
*/
public class MainActivity extends ActionBarActivity {
private Button button;
private TextView tv;
private Handler handler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)this.findViewById(R.id.button1);
handler = new Handler(){ public void handleMessage(android.os.Message msg) { Bundle bundle = msg.getData();
String data = bundle.getString("color");
MainActivity.this.button.append(data);
};
};
final Runnable runnable = new Runnable() { @Override
public void run() {
// TODO Auto-generated method stub
String color = "red";
Message message = new Message();
Bundle bundle = new Bundle();
bundle.putCharSequence("color", color);
message.setData(bundle);
MainActivity.this.handler.sendMessage(message);
try {
Thread.sleep(3000);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
};
button.setOnClickListener(new OnClickListener() { @Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
new Thread(runnable).start();
}
});
} }
自己随便写的一个demo,记录一下。