handler+looper传值更改activity的UIreact
博客开了一段时间,一直想写点本身的学习经验及体会,等着之后长时间不用再要用到的时候直接拿过来上手。想了想,以前用到handler,android
看了几篇文章感受不是很详细。今天就来说讲handler。json
android用handler传值更改UI有两个目的:1、从用户体验方面考虑,把繁杂的操做和计算过程放到其余线程,是主线程(用户界面)更安全
加的流畅,减小出现卡顿现象。ide
2、确保线程安全,只有主线程能更改UI;oop
利用handler传值,须要建立looper对象(系统在建立主线程(activity)的时候,在activity内部封装了一个looper对象,即看不到新建学习
looper对象),系统会为每一个looper建立an一个消息队(messagequene),经过handler的sendmessage方法发送消息给该looper的消息ui
队列,而后在该线程中,handler会从消息队列中取出message,经过message.what来判断接收的message进行什么操做(更改该线程的ui等)。spa
若是你想在其余的线程里面进行操做以后发message给UI线程改变UI,就必需要确保你的handler发送的消息必须发送到该UI线程的消息队列(messagequene),线程
最简单的办法就是使用UI线程的handler进行发送message(即sendmessage),下面说两种方法使操做的线程得到UI线程的handler:
1、在操做线程中:Handler handler=MainActivity.handler;若是你要更改UI,就要在MainActivity里面
定义一个handler属性而且要是静态的(static),这样把handler的实例化最好放在oncreact方法里面
(固然,handler实例化能够放在类里面的任何地方),在handler的实例化对象里面重写 handleMessage(Message msg)
方法,在handleMessage方法里面进行接收消息并进行操做改变UI。
2、定义一个有handler属性的类,在类里面添加get和set方法用来获取和实例化handler;
下面看代码吧:
UI线程
public class MainActivity extends DroidGap { public static Handler handler; @Override public void onCreate(Bundle savedInstanceState) { // Be sure to call the super class. super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); if (msg.what == 100) { //这里面写代码更改UI } else if (msg.what == 101) { //这里面写代码更改UI } else if (msg.what == 102) { } }
操做类:
public boolean add(JSONArray json) { try { JSONArray jsonArray=json.getJSONArray(0); JSONObject jsonObject= (JSONObject) (jsonArray.get(0)); final PrintItem printItem=new PrintItem(jsonObject.getString("product"),jsonObject.getInt("count"),jsonObject.getInt("price")); list.add(printItem); handler=MainActivity.handler; Message message=new Message(); message.what=100; message.obj=printItem; handler.sendMessage(message); return true; } catch (Exception e) { e.printStackTrace(); } return false; }