Saturday 6 April 2019

handler - Understanding what Looper is about in Android

I had to add Looper to the following code:




public class MyRunnable implements Runnable
{
@Override
public void run()
{
Looper.prepare();
final Looper looper = Looper.myLooper();

new Handler().postDelayed(
new Runnable()

{
@Override
public void run()
{
try
{
}
catch (Exception ex)
{
}

finally
{
looper.quit();
}
}
}, 100);

Looper.loop();
}
}



Notice that I have a runnable inside a runnable. The nested runnable gets executed through a Handler. Initially I didn't have Looper but Android complained that I needed to call Looper.prepare before executing another thread.



I read up on Looper but it still seems kind of cryptic. It seems to act like some kind of internal messaging pipeline. It isn't clear to me why this is necessary since there are no messages going from my outer runnable to my inner runnable. Even though that is true, it seems that Android just makes the hard rule that if you call a thread from a thread, you MUST also call Looper.prepare. Even if I accept that as-is, it still doesn't help to understand why I need to call looper.loop and looper.quit. If I omit Looper.loop, my Handler never runs and that is what isn't clear. What does Looper.loop do that allows my Handler to run?

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...