Android的多线程

今天来总结一下Android的多线程,分别介绍一下四种方法。『原理都是:子线程发消息到主线程进行更新UI』

    1.Activity.runOnUiThread(Runnable)
    2.View.post(Runnable),View.postDelay(Runnable,long)
    3.Handler
    4.AsyncTask

----------------------------------------------------------------------------------------------------------------

    1.Activity.runOnUiThread(Runnable)

利用Activity.runOnUiThread(Runnable)把更新ui的代码创建在Runnable中,然后在需要更新ui时,把这个Runnable对象传给Activity.runOnUiThread(Runnable)。 Runnable对像就能在ui程序中被调用。如果当前线程是UI线程,那么行动是立即执行。如果当前线程不是UI线程,操作是发布到事件队列的UI线程。

public class TestActivity extends Activity {
    Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.handler_msg);
        btn = (Button) findViewById(R.id.button);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        // 模拟耗时的操作。
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        // 更新主线程UI
                        TestActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                btn.setText("更新完毕!");
                            }
                        });
                    }
                }).start();
            }
        });
    }
}


2.1View.post(Runnable)


mTextView.post(new Runnable() {
    @Override
    public void run() {
        mTextView.setText("yes, 获取到数据了!#");
        mTextView.setBackgroundColor(Color.BLUE);
    }
});
2.2 View.postDelay(Runnable,long)

Android View 都有一个postDelayed(Runnable,毫秒数),用于延迟UI操作的方法,下面的代码中就是300毫秒之后,calendar_view才显示

private void method() {
    blur_view.setBackgroundColor(Color.BLACK);
    blur_view.postDelayed(new Runnable() {
        public void run() {
            calendar_view.setVisibility(View.GONE);
            CalendarActivity.this.finish();
        }
    }, 300);
}

5秒钟倒计时

        num = (TextView) findViewById(R.id.num);
        num.postDelayed(new Runnable() {
            @Override
            public void run() {
                num.setText("" + index);
                index--;
                if (index == 0) {
                    Intent intent = new Intent(MainActivity.this, SecondActivity.class);
                    startActivity(intent);
                } else {
                    num.postDelayed(this, 1000);
                }
            }
        }, 1000);

3.Handler的机制

Android的主线程叫UI线程,从名字可知主线程主要是用来创建,更新UI的。所以耗时操eg:网路访问,文件处理,多媒体处理,等都需要在子线程中完成。(为了保证UI流畅度嘛)此时就需要Handler。充当子线程与主线程之间的桥梁。

 通常将handler声明在Activity中,然后覆写Handler 中的handleMessage方法,当子线程调用handler.sendMessage()方法后,handleMessage方法将会在主线程中执行。

Handler,Message,Looper,MessageQueue等对象的关系。

主线程中Android默认调用Looper.prepare()方法。调用的目的是:在Looper中创建MessageQueue成员变量,并把Looper对象绑定到当前线程中。当子线程调用Handler的sendMessage(对象)方法时候,就将Message对象添加到Looper创建的MessageQueue队列中,同时给Message指定了Handler对象。主线程默认执行了Looper.looper() 方法,该方法从Looper的成员变量MessageQueue中取出Message,然后调用Message的handler对象的handleMessage()方法。这样就完成了整个消息机制。

4.AsyncTask.

AsyncTask是种轻量级的异步任务类。

官方API翻译:

AsyncTask使适当的和易用的UI线程。这个类可以执行后台操作,并在用户界面上发布结果,而不必处理线程/或处理程序。

AsyncTask的设计是围绕线程和处理器的一个辅助类,并不构成一个通用的线程框架。asynctasks应该用于短作业(最多。几秒钟)如果你需要保持线程运行很长一段时间,我们强烈建议您使用不同的java.util.concurrent包如执行API提供的,线程池和futuretask。

异步任务被定义为一个在后台线程上运行的运算,其结果是在用户界面上发布的。一个异步任务是由3的泛型类型定义为参数,过程和结果,和4个步骤,称为onpreexecute,doInBackground,onProgressUpdate和onpostexecute。

AsyncTask必须被子类继承使用。子类至少重写一个方法(doInBackground(Params...)),最经常会重写第二个方法(onPostExecute(result))

使用案例:


调用方式


AsyncTask的泛型

一个异步任务使用的三种类型如下:

1.Params,the type of the parameters sent to the task upon execution.(在执行时发送到任务的参数类型

2.Progress,the type of the progress units published during the background computation.(后台计算过程中的进度单元的类型。)

3.Result,the type of the result of the background computation.(后台运行的结果类型。)

(不是所有的参数都需要,不用时可以返回void类型)

onPreExecute     执行顺序的第一个。可以进行一些初始化操作(运行在主线程中)!

doInBackground  执行一些耗时操作,将结果数据返回(运行在子线程中)!

onPostExecute    显示结果数据更新UI(运行在主线程中)!

task.execute(参数) 调用的方法在主线程中!

Note:

1.由于Handler需要和主线程交互,而Handler又是内置于AsyncTask中,所以AsyncTask的创建必须在主线程。

2.AsyncTaskResult的doInBackground(Params)方法执行异步任务运行在子线程中,其他方法运行在主线程中,可以操作UI组件。

3.不要手动的去调用AsyncTask的onPreExecute, doInBackground, publishProgress, onProgressUpdate, onPostExecute方法,这些都是由android系统自动调用的。

4.一个AsyncTask任务只能被执行一次。

5.运行中可以随时调用cancel(boolean)方法取消任务,如果成功调用isCancel()会返回true,并不会执行onPostExecute(),取而代之的是调用onCancelled()。从源码看,如果这个任务已经执行了这个时候调用cancel是不会真正的把task结束,而是继续执行,只不过改变的是执行之后的回调方法的onPostExecute还是onCancelled.


猜你喜欢

转载自blog.csdn.net/gjy211/article/details/72818683