package async_demo;
import com.exercise.R;
import com.exercise.R.layout;
import com.exercise.R.menu;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ProgressBar;
import android.widget.TextView;
public class AsyncTask_Handler extends Activity {
TextView asynctask_textView;
TextView handler_textview;
MyHandler handler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.async_task);
asynctask_textView=(TextView) findViewById(R.id.asynctask_textview);
asynctask_textView.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Asynctask task=new Asynctask();
task.execute();
}
});
handler_textview=(TextView) findViewById(R.id.handler_textview);
handler_textview.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
handler=new MyHandler();
MyThread mt=new MyThread();
new Thread(mt).start();
}});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.async_task, menu);
return true;
}
class Asynctask extends AsyncTask<String, ProgressBar, String>{
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String text="AsynacTask_Change";
return text;
}
@Override
protected void onCancelled(String result) {
// TODO Auto-generated method stub
super.onCancelled(result);
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
asynctask_textView.setText(result);
//在asynctask中修改UI
}
@Override
protected void onProgressUpdate(ProgressBar... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
}
class MyHandler extends Handler{
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
if (msg.what==1010){
Bundle b=msg.getData();
String textString =b.getString("text");
AsyncTask_Handler.this.handler_textview.setText(textString);
//在handler中修改ui
};
}
}
class MyThread implements Runnable{
@Override
public void run() {
// TODO Auto-generated method stub
Message msg=new Message();
Bundle bundle=new Bundle();
bundle.putString("text","Change" );
msg.setData(bundle);
msg.what=1010;
AsyncTask_Handler.this.handler.sendMessage(msg);
}
}
}