手动Handler与Thread处理UI数据同步问题

(1)在Android 2.3以前,为防止ANR(Application Not Responding),Google是不赞成将网络连接等一系列耗时操作直接放到应用主线程进行的,推荐将这类操作放在子线程内;而Android 4.0版本开始,Google强制要求这类操作必须在子线程内进行,否则将抛出 NetworkOnMainThreadException 异常。

(2)操作UI必须只能在主线程内进行,否则报“Can’t create handler inside thread that has not called Looper.prepare()”错误。注意Toast 也属于UI操作


Thread与Handler的简单使用:

public class TestActivity extends Activity {
	//自定义数据处理handler
    private Handler myHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
			//更新UI数据
            if (msg.what == 1) {
                String message = (String) msg.obj;
                Toast.makeText(TestActivity.this, message, Toast.LENGTH_SHORT).show();
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.test);
        
        Button btnLoad = (Button) this.findViewById(R.id.btnLoad);
        btnLoad.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
				Thread thread = new Thread() {
					@Override
					public void run() {
						try {
							Thread.sleep(1000*10);  
							
							Message message = new Message();
							message.what = 1;
							message.obj = "测试调用完成";
							
							//向主线程发送数据
							myHandler.sendMessage(message);
						} catch (Exception e) {
							e.printStackTrace();
							Log.e(TestActivity.class.toString(), e.getMessage());
						}
					}
				};
				thread.start();
            }
        });
    }
}


你可能感兴趣的:(手动Handler与Thread处理UI数据同步问题)