java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

来源:互联网 发布:js正则表达式 i 编辑:程序博客网 时间:2024/06/05 17:02

在Android中不允许Activity里新启动的线程访问该Activity里的UI组件,这样会导致新启动的线程无法改变UI组件的属性值。

出现java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()异常

然而,我们实际需要,在很多时候都需要异步获取数据刷新UI控件,这时候采取的方法就是Handler消息机制和AsyncTask异步任务两种解决方法。

首先是引起异常的例子:

 

new Thread(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubtry {Thread.sleep(1000);Toast.makeText(getApplicationContext(), "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 0).show();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}).start();


上面例子在线程里面休眠1秒后吐司消息,然后出现java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()异常。

正确的方法应该是:

new Thread(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubtry {Thread.sleep(1000);handler.sendEmptyMessage(0);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}).start();
private Handler handler = new Handler() {@Overridepublic void handleMessage(Message msg) {// TODO Auto-generated method stubToast.makeText(getApplicationContext(), "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 0).show();}};

重写Handler对象中的handlerMessage方法进行你需要的处理。

当然不是只有这一种方法可以实现我们的需要,

runOnUiThread(Runnable action) Activity中带有的方法,运行指定的action在UI线程中,如果当前线程是UI线程,那么action立即执行。如果当前线程不是UI线程,那么action将发送事件到UI的消息队列中。

View post(Runnable aciton);

View postDelayed(Runnable action, long delayMillis);

这两个方法也是同样的道理。

下面是异步任务的处理:

private class MyTask extends AsyncTask<Void, Void, Void> {@Overrideprotected Void doInBackground(Void... params) {// TODO Auto-generated method stubpublishProgress();return null;}@Overrideprotected void onProgressUpdate(Void... values) {// TODO Auto-generated method stubsuper.onProgressUpdate(values);try {Thread.sleep(1000);Toast.makeText(getApplicationContext(), "doInBackground", 0).show();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}@Overrideprotected void onPostExecute(Void result) {// TODO Auto-generated method stubToast.makeText(getApplicationContext(), "onPostExecute", 0).show();super.onPostExecute(result);}}

onProgressUpdate方法的执行在收到publishProgress方法调用后,运行于UI线程中,对UI控件进行处理,例如,我们做的下载,需要显示下载到了百分之多少时,可以不停的publishProgress(Value value),然后在进度条中更新。

onPostExecute()方法,在doInBackground()方法结束后运行在UI线程,对result进行处理

 

doInBackground()方法中,就是在后台线程中处理我们的异步任务,不能做类似Toast的操作,同样会出java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()异常。

0 0