在非Activity(非主线程)中更新UI的办法:(一)Handler+Thread+Activity静态成员变量

先介绍第一种方法,直接通过Handler对象更新UI,比较投机取巧,但是也能用。

1、在Activity中自定义ViewHandler,在ViewHandler中对UI进行处理,

class ViewHandler extends Handler {
		public ViewHandler() {
		}

		// TODO Auto-generated constructor stub

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

	}

但是ViewHandler的声明必须放在主线程中,比如OnCreate方法中,通过Activity的instance对象去得到Handler,


public class MainActivity extends Activity {
	
	ViewHandler handler = new ViewHandler();
	public static MainActivity instance;

	public ViewHandler getHandler() {
		return handler;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		bar = (ProgressBar) findViewById(R.id.progress_horizontal);
		//得到一个静态成员变量,需要在onDestroy方法中释放,不然有可能内存泄漏
		this.instance = this;
	}

在非Activity中如果要更新UI,可以通过如下方式,需要另起一个线程,否则会报ANR

public class OperProgress {
	public void setPro() {
		Thread thread = new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				int i = 0;
				while (i < 100) {
					i++;
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					Message msg = new Message();
					msg.arg1 = i;
					//通过静态成员变量得到ViewHandler,从而更新UI
					MainActivity.instance.getHandler().sendMessage(msg);
				}
			}
		});
		thread.start();
	}
}



你可能感兴趣的:(android)