两种缓解AndroidUI界面首次进入慢方式分析:Hanlder,AsyncTask

在主线程中new 的Handler其实是只是一种延后到主线程其他消息队列后执行,而AsyncTask是另起线程完成后再回到主线程待主线程使用。 

简单说就是,Handler的事都是UI主线程做,只不过不用马上做,而AsyncTask把不该UI线程做的事交给另一个线程,然后等拿到结果再还给UI线程处理,具体请看代码及打印。

代码:

public class Main2Activity extends AppCompatActivity implements View.OnClickListener{
    private Button handlerBtn,anycTaskBtn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        handlerBtn = (Button) findViewById(R.id.button4);
        anycTaskBtn = (Button) findViewById(R.id.button5);
        handlerBtn.setOnClickListener(this);
        anycTaskBtn.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {

        if(v.getId() == R.id.button4){

            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    Log.d("Main2Activity","handler current Thread = " + Thread.currentThread().getId());
                }
            });
        }else if(v.getId() == R.id.button5){
            task.execute("a");
        }

    }

    private Handler mHandler = new Handler() ;
    private AsyncTask task = new AsyncTask() {
        @Override
        protected Object doInBackground(Object[] params) {
            Log.d("Main2Activity","AsyncTask doInBackground current Thread = " + Thread.currentThread().getId());
            return null;
        }

        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);
            Log.d("Main2Activity","AsyncTask onPostExecute current Thread = " + Thread.currentThread().getId());
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            Log.d("Main2Activity","AsyncTask onPreExecute current Thread = " + Thread.currentThread().getId());
        }
    };
}

执行后打印结果:

12-13 20:35:09.584 D/Main2Activity( 3358): handler current Thread = 1

12-13 20:35:11.790 D/Main2Activity( 3358): AsyncTask onPreExecute current Thread = 1

12-13 20:35:11.795 D/Main2Activity( 3358): AsyncTask doInBackground current Thread = 19569

12-13 20:35:11.807 D/Main2Activity( 3358): AsyncTask onPostExecute current Thread = 1

线程id为1,表示UI主线程,其他为子线程。

你可能感兴趣的:(handler,AsyncTask)