为什么抱怨我的代码没有调用Looper.prepare()

时间:2013-10-04 14:50:03

标签: android performance android-intent looper

我创建了一个 Looper线程类:

public class MyLooperThread extends Thread{
    private Handler mHandler;

    public void init(){
         start(); //start the thread

         synchronized (this) {
            wait(5000); //wait for run()
         }
         Log.d("DEBUG","Init Done!");

         //EXCEPTION: Can't create handler inside thread that has not called Looper.prepare()
         MyObject obj = new MyObject(mHandler);
   }

    @Override
    public void run() {
        Looper.prepare();

        mHandler = new Handler(){
           @Override
           public void handleMessage(Message msg){
            //Check installed app package names, NOTHING RELATED WITH UI                ...
            }
        };
        synchronized (this) {
            notify(); 
        }
        Looper.loop();

     }//end of run()
}

在我的活动中,我在MyLooperThread中调用了init()的{​​{1}}方法。此外,我有一个onCreate()元素,当选中ToggleButton时,我也会调用ToggleButton的{​​{1}}方法。

MyLooperThread

启动我的应用时,没关系。我的切换按钮默认显示为已选中。当我取消选中它时再次检查,我得到例外:

init()

指向public class MyActivity extends Activity implements OnCheckedChangeListener{ … @Override protected void onCreate(Bundle savedInstanceState){ … myToggleButton.setOnCheckedChangeListener(this); myToggleButton.setChecked(true);//checked by default MyLooperThread myLooper = new MyLooperThread(); myLooper.init(); } @Override public void onCheckedChanged(CompoundButton button, boolean isChecked) { if(isChecked){ MyLooperThread myLooper = new MyLooperThread(); myLooper.init(); }else{ ... } } } 方法的最后一行代码java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

为什么我收到此异常?我不明白,我在init()中调用MyObject obj = new MyObject(mHandler);后创建了mHandler

3 个答案:

答案 0 :(得分:1)

非常确定错误是说你在UI线程上没有尝试做与UI相关的事情。

答案 1 :(得分:0)

由于你没有在handleMessage内发布任何你正在做的事情,我会假设你正试图改变其中一个UI元素。始终使用UI线程更新UI。它应该是这样的:

handleMessage(Message msg) {
    ...
    getActivity().runOnUiThread(new Runnable {
        ...
        // update UI here
        ...
    });
    ...
}

答案 2 :(得分:0)

只需使用HandlerThread():

ht = new HandlerThread();
ht.start();
h = new Handler(ht.getLooper());