Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Android-异步操作更新UI界面的几种方法 #22

Open
jeffrey1995 opened this issue Nov 28, 2016 · 0 comments
Open

Android-异步操作更新UI界面的几种方法 #22

jeffrey1995 opened this issue Nov 28, 2016 · 0 comments

Comments

@jeffrey1995
Copy link
Owner

jeffrey1995 commented Nov 28, 2016

在Android开发中,耗时操作是比较多的,更新ui需要在主线程中,然而耗时操作是不能放在主UI线程中在执行的,因为这样会使我们的主UI界面不流畅甚至严重卡顿,所以需要使用异步操作来做更新UI界面的操作,方法的实质就是将耗时操作放到一个新的线程中来执行,并在必要时通知UI线程做出更新的动作。
最常有的有四种方法:

1.Handler

Handler handler= new Handler() {
@OverRide
public void handleMessage(Message msg) {
super.handleMessage(msg);
//操作界面...
}
};

public class MyThread extends Thread {
public void run() {
​ ​ ​ // 耗时操作...
Message msg = new Message();
handler.sendMessage(msg);//向Handler发送消息,
}
}
在MyThread线程中进行耗时操作,在执行完之后,创建一个Message对象(可以附带其他参数:what、arg1/2...),调用handler的sendMessage将Message对象发出,信息对象会到MessageQueue,Looper负责轮询MessageQueue,将其中的Message转发到对应的handler,回调handleMessage函数进行处理,在这里可以进行ui操作(因为Handler是在主线程中定义的,所以回调函数执行在主线程)

2. AsyncTask

//UI线程中执行
new LoadTask().execute( "《uri》" );

private class LoadTask extends AsyncTask {
protected String doInBackground( String... url ) {
return loadDataFormNetwork( url[0] );//后台耗时操作
}

protected void onPostExecute( String result ) {
myText.setText( result ); //得到来自网络的信息刷新页面

}
这是Android里自带的一个框架,也是基于Handler、Looper机制的。但是比较简洁、逻辑清晰。

3.View.post(Runnable runnable)

public void onClick( View v ) {
new Thread( new Runnable() {
public void run() {
// 耗时操作
​ ​ ​ ​ ​ ​ loadNetWork();
​ textView.post(new Runnable() {
@OverRide
public void run() {
textView.setText("data");
}
});
}
}).start();
}
在新的线程中进行耗时操作,需要更新ui界面是,通过调用控件的引用调用post方法,在run方法中更新ui界面。

4.Activity.runOnUiThread(Runnable runnable)

public void onClick( View v ) {
new Thread( new Runnable() {
public void run() {
// 耗时操作
​ ​ ​ ​ ​ ​ loadNetWork();
​ Activity.runOnUiThread.( new Runnable() {
@OverRide
public void run() {
textView.setText("data");
}
});
}
}).start();
}
与3方法类似,只不过是通过Activity的引用调用runOnUiThread方法,在run方法中更新ui界面。

以上4种方法是Android最为常用的异步操作方法,还有一个第三方框架——Rxjava,逻辑十分清晰,也值得一用,具体可以参考文章RxJava 详解

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant