用Handler在线程间传送数据

之前一直都把耗时操作放在新线程里处理,包括添加修改ListView的Item,处理完了再用handler发个EmptyMessage,执行listAdapter.notifyDataSetChanged(),但我发现用这种方法经常会出现java.lang.IllegalStateException:The content of the adapter has changed but ListView did not receive a notification异常.即使在notifyDataSetChanged()前把listview隐藏。
其实可以通过把数据传给handler,添加删除清空什么的操作都让handler来处理,这样就不会出错。
传送数据是用Bundle,用过Intent应该很熟悉,不解释:


package com.pocketdigi.test3;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class main extends Activity {
    /** Called when the activity is first created. */
	TextView tv;
	Button btn;
	Handler handler;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        tv=(TextView)findViewById(R.id.tv);
        btn=(Button)findViewById(R.id.btn);
        handler=new Handler(){

			@Override
			public void handleMessage(Message msg)
			{
				// TODO Auto-generated method stub
				super.handleMessage(msg);

				switch(msg.what)
				{
				case 1:
					Bundle bundle=msg.getData();
					System.out.println(bundle.get("add"));
					break;
				}
			}
        	
        };
        btn.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v)
			{
				// TODO Auto-generated method stub
				Message msg = handler.obtainMessage();
				msg.what=1;
				Bundle bundle = new Bundle();
				bundle.putString("add", "sdfasdfasf");
				msg.setData(bundle);
				handler.sendMessage(msg);
//				handler.sendEmptyMessage(0);
			}});
    }
}

© 2011, 冰冻鱼. 请尊重作者劳动成果,复制转载保留本站链接! 应用开发笔记