【Monica的android学习之路】Activity的线程异步处理

  • Post author:
  • Post category:其他


【Monica的android学习之路】Activity的线程异步处理



1.优缺点

两者均是为了实现线程异步处理,适用于用多线程处理Activity中的耗时操作

AsyncTask:单个异步线程时,AsyncTask适用,他是为了简化异步处理而设计的一个轻量化异步类;简单易用,但处理多个后台线程时会变得困难。(底层还是用了Handler机制,实际内存开销更大)

Handler:适用于单个(个人认为处理单个任务代码也比较简单)或多个后台线程,处理灵活。



2.AsyncTask

MainActivity的onCreate中调用

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i(TAG, "onCreate activity");
        setContentView(R.layout.activity_main);
        TextView web = findViewById(R.id.web);
        Button cancel = findViewById(R.id.cancel);
        MyTask myTask = new MyTask();
        myTask.execute(web);  //执行AsyncTask任务,传入参数类型为TextView
        cancel.setOnClickListener(v -> {
            myTask.cancel(true);   //执行AsyncTask的取消任务,调用onCancelled()
        });
    }

AsyncTask类:

public class MyTask extends AsyncTask<TextView, StringBuilder, Boolean> {
//    参数类型分别为:
//    调用方excute()中传入的参数类型;
//    publishProgress()显示进度时使用的参数类型,对应onProgressUpdate()的参数类型
//    doInBackground()返回值类型,即任务执行完成后返回的类型,对应onPostExecute()的参数类型
    private static final String TAG = "monica";
    private TextView textView;

    @Override
    protected void onPreExecute() {
        Log.i(TAG, "onPreExecute");
    }

    @Override
    protected Boolean doInBackground(TextView... textViews) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (textViews.length > 0) {
            textView = textViews[0];
        }
        while (true) {
            stringBuilder.append("*");
            publishProgress(stringBuilder); //更新进度,调用onProgressUpdate
            if (stringBuilder.length() > 100) {
                break;
            }
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return true;         //耗时任务执行完毕,调用onPostExecute
    }

    @Override
    protected void onProgressUpdate(StringBuilder... values) {
        textView.setText(values[0]);
    }

    @Override
    protected void onPostExecute(Boolean s) {
        if (s) {
            textView.setText(new String("completed"));
        } else {
            textView.setText(new String("failed"));
        }
    }

    @Override
    protected void onCancelled(Boolean aBoolean) {
        Log.i(TAG, "task onCancelled");
        textView.setText("task onCancelled");
    }
}



3.Handler

使用方法:

(1)实例化一个handler对象,在handleMessage中实现msg处理逻辑

(2)在异步线程中,随时可以实例化一个Message对象,调用sendMessage方法发送一个消息到MessageQueue。Looper循环从队列中取出消息给handleMessage处理,实现异步线程与主线程的交互

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "monica";
    private static TextView web;
    @SuppressLint("HandlerLeak")
    private static Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            Log.e(TAG, "begin setText");
            switch (msg.what) {
                case 1:
                    web.setText(msg.obj.toString());
                    break;
                default:
                    web.setText("error");
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i("zengwang", "onCreate activity");

        setContentView(R.layout.activity_main);
        web = findViewById(R.id.web);
        ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 4, 10L,
                TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(2));
        executor.execute(new Runnable() {
            @Override
            public void run() {
                Message msg = new Message();
                msg.what = 1;
                msg.obj = "a new Thread";
                handler.sendMessage(msg);
            }
        });
    }
}



版权声明:本文为Monica_s_sweet原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。