Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy complains my code has not called Looper.prepare()
    text
    copied!<p>I created a <strong>Looper thread</strong> class:</p> <pre><code>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() } </code></pre> <p>In my <strong>Activity</strong>, I call above <code>MyLooperThread</code> 's <code>init()</code> method in <code>onCreate()</code>. Besides, I have a <code>ToggleButton</code> element, when <code>ToggleButton</code> is checked, I call <code>MyLooperThread</code>'s <code>init()</code> method too. </p> <pre><code>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{ ... } } } </code></pre> <p>When launch my app, it is fine. My toggle button is shown as checked by default. When I uncheck it &amp; check it again, I got <strong>exception:</strong> </p> <pre><code>java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare() </code></pre> <p>which is pointed to the <code>init()</code> method's last line of code <code>MyObject obj = new MyObject(mHandler);</code></p> <p><strong>Why I got this exception?</strong> I don't understand, my <code>mHandler</code> is created after I called <code>Looper.prepare()</code> in <code>run()</code>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload