0

我创建了一个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()
}

在我的Activity中,我调用了上面MyLooperThreadinit()方法onCreate()。此外,我有一个ToggleButton元素,当ToggleButton被检查时,我也调用MyLooperThread'sinit()方法。

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是在我调用之后创建Looper.prepare()run()

4

3 回答 3

1

很确定错误是说您在不在 UI 线程上时尝试执行与 UI 相关的操作。

于 2013-10-04T14:51:42.497 回答
0

只需使用 HandlerThread():

ht = new HandlerThread();
ht.start();
h = new Handler(ht.getLooper());
于 2013-10-04T15:30:28.553 回答
0

由于您尚未在 中发布您正在执行的任何操作,因此handleMessage我假设您正在尝试更改其中一个 UI 元素。始终使用 UI 线程来更新 UI。它应该是这样的:

handleMessage(Message msg) {
    ...
    getActivity().runOnUiThread(new Runnable {
        ...
        // update UI here
        ...
    });
    ...
}
于 2013-10-04T15:27:19.317 回答