Android的线程利器之AsyncTask
Android的线程利器之AsyncTask
java自带的线程已经慢不错的了,在Android里又进了一步。一开始,在java传统的Thread和Runnable里加上了handler就已经蛮不错的了,handler作为信息调配的中转站,让人用的很输入,线程就只管去计算,分配的事就不要你做了。我写的东西有点杂乱无章,呵呵。再后来就到了高级一点的HandlerThread,把资源费配的Handler和线程Thread放在了一起,我比较喜欢的是,重新启动一个线程非常的方便。
- new HandlerThread().start();
这样一下就可以了,线程已经被启动,而且可以调用HandlerThread类自带的。然后调用getLooper调取线程里的消息循环,送入handleMessage来处理。
getLooper是HandlerThread也是帮我们封装好了的。
如果要自己打包消息循环就可以这样做,JDK文档上就是这么写的:
- class LooperThread extends Thread {
- public Handler mHandler;
- public void run() {
- Looper.prepare();
- mHandler = new Handler() {
- public void handleMessage(Message msg)
- { // process incoming messages here
- }
- };
- Looper.loop();
- }
- }
Threads by default do not have a message loop associated with them; to create one, call prepare()
in the thread that is to run the loop, and then loop()
to have it process messages until the loop is stopped
线程默认是不会有一个与之相关的消息队列,你必须调用prepare()方法来创建,然后用静态方法loop()来将消息加入进去,知道循环的结束。
以上"传统"的方式还是比较的负责,当我们拥有了HandlerThread后一切边的比较的简单了:
- HandlerThread ht = new HandlerThread("thread");
- ht.start();
- //ht.getLooper():从名字为thread的线程读取消息循环
- //然后,new myHandler将该消息循环调入Handler中处理,handler读取消息循环里面的消息,handleMessage来分配出来消息
- myHandler h = new myHandler(ht.getLooper());
- private class myHandler extends Handler{
- public myHandler(Looper looper){
- //super:Use the provided queue instead of the default one.
- //将从“thread”得到的队列来替换默认的队列,应该是加入到替换UI队列,因为这里的handler主线程中的
- super(looper);
- }
- int i = 0 ;
- @Override
- public void handleMessage(Message msg){ super.handleMessage(msg);
- //do something
- }
- }
- //将线程progressThread添加如线程消息队列
- //这里我理解是将改线程加入整个进程的线程队列中
- h.post(progressThread);//Causes the Runnable r to be added to the message queue.
- Runnable progressThread = new Runnable(){
- @Override
- public void run() {
- Bundle b =new Bundle();
- Message msg = h.obtainMessage();
- b.putInt("a",11);
- b.putString("b", "bbb");
- msg.setData(b);
- msg.sendToTarget();
- try {
- Thread.sleep(2000);
- h.post(progressThread);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- };
一般,情况下这里的东西已经很适用,但是google就是技术届的大哥大,非要把技术更上一层楼,所有有出现了:AsyncTask
这个东西非常的好,比HandlerThread封装的还要厉害。先看代码
- package com.test;
- import android.app.Activity;
- import android.app.AlertDialog;
- import android.app.AlertDialog.Builder;
- import android.content.DialogInterface;
- import android.os.AsyncTask;
- import android.os.Bundle;
- import android.util.Log;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.EditText;
- import android.widget.LinearLayout;
- import android.widget.TextView;
- public class CopyOfAsyncTaskTestActivity extends Activity {
- /** Called when the activity is first created. */
- private TextView ctext ;
- private Button startButton;
- private Button endButton;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- findViews();
- ctext.setText("原来是这个");
- Log.i("System.out", "onCreate-->" + Thread.currentThread().getName());
- startButton.setOnClickListener(new View.OnClickListener() {
- public void onClick(View v) {
- openDialog();
- Log.i("System.out", "onClick-->" + Thread.currentThread().getName());
- }
- });
- }
- private class myAsyncTask extends AsyncTask<String,Void,String>{
- @Override
- protected String doInBackground(String... params) {
- // TODO Auto-generated method stub
- Log.i("System.out", "doInBackground-->" + Thread.currentThread().getName());
- return params[0];
- }
- @Override
- protected void onCancelled() {
- // TODO Auto-generated method stub
- super.onCancelled();
- }
- @Override
- protected void onPostExecute(String result) {
- // TODO Auto-generated method stub
- ctext.setText(result);
- Log.i("System.out", "onPostExecute-->" + Thread.currentThread().getName());
- super.onPostExecute(result);
- }
- @Override
- protected void onPreExecute() {
- Log.i("System.out", "onPreExecute-->" + Thread.currentThread().getName());
- // TODO Auto-generated method stub
- super.onPreExecute();
- }
- @Override
- protected void onProgressUpdate(Void... values) {
- // TODO Auto-generated method stub
- Log.i("System.out", "onProgressUpdate-->" + Thread.currentThread().getName());
- super.onProgressUpdate(values);
- }
- }
- private void openDialog(){
- final String dialogstr=null;
- AlertDialog.Builder alert = new AlertDialog.Builder(CopyOfAsyncTaskTestActivity.this);
- alert.setTitle("请输入");
- final EditText input = new EditText(CopyOfAsyncTaskTestActivity.this);
- alert.setView(input);
- alert.setPositiveButton("Ok",
- new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int whichButton) {
- String value = input.getText().toString();
- Log.i("System.out", "value-->" + value);
- new myAsyncTask().execute(value);
- }
- });
- alert.setNegativeButton("Cancel",
- new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog,int whichButton){
- }
- }
- );
- alert.show();
- }
- private void findViews(){
- ctext=(TextView)findViewById(R.id.ctext);
- startButton=(Button)findViewById(R.id.startButton);
- endButton=(Button)findViewById(R.id.endButton);
- }
- }
|
评论暂时关闭