Android子线程创建Handler方法

如果我们想在子线程上创建Handler,通过直接new的出来是会报异常的比如:

new Thread(new Runnable() {
			public void run() {
				Handler handler = new Handler(){
					@Override
					public void handleMessage(Message msg) {
						Toast.makeText(getApplicationContext(), "handler msg", Toast.LENGTH_LONG).show();
					}
				};
				handler.sendEmptyMessage(1);
				
			};
		}).start();

会报错:

01-12 02:49:31.814: E/AndroidRuntime(2226): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

1.方法1(直接获取当前子线程的looper)

既然它说要 Looper.prepare(),那我们就给他prepare()咯

new Thread(new Runnable() {
			public void run() {
				Looper.prepare();  // 此处获取到当前线程的Looper,并且prepare()
				Handler handler = new Handler(){
					@Override
					public void handleMessage(Message msg) {
						Toast.makeText(getApplicationContext(), "handler msg", Toast.LENGTH_LONG).show();
					}
				};
				handler.sendEmptyMessage(1);
				
			};
		}).start();


然后我们再运行,发现不报错了,但是handleMessage内的代码没执行,因为还差重要的一步,Looper.loop();最终代码是

new Thread(new Runnable() {
			public void run() {
				Looper.prepare();
				Handler handler = new Handler(){
					@Override
					public void handleMessage(Message msg) {
						Toast.makeText(getApplicationContext(), "handler msg", Toast.LENGTH_LONG).show();
					}
				};
				handler.sendEmptyMessage(1);
				Looper.loop();
			};
		}).start();

这样就OK了


2.方法2(获取主线程的looper,或者说是UI线程的looper)

这个方法简单粗暴,不过和上面的方法不一样的是,这个是通过主线程的looper来实现的

new Thread(new Runnable() {
			public void run() {
				Handler handler = new Handler(Looper.getMainLooper()){ // 区别在这!!!!
					@Override
					public void handleMessage(Message msg) {
						Toast.makeText(getApplicationContext(), "handler msg", Toast.LENGTH_LONG).show();
					}
				};
				handler.sendEmptyMessage(1);
			};
		}).start();





你可能感兴趣的:(Android)