i am programing something in android, and i want to create a delay.
when i add to my activity class thread, the app stack after implement data to variable,
but when i use handler(with postDelay) it works fine.
1.why?
the code (mapView and userPointOverlay are class private local variables):
using thread:
new Thread(new Runnable() //2.5sec delay between switches
{
@Override
public void run()
{
try
{
Thread.sleep(5000);
mapView.getOverlays().remove(userPointOverlay);
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
}).start();
using handler:
handler.postDelayed(new Runnable()
{
@Override
public void run()
{
mapView.getOverlays().remove(userPointOverlay);
}
}, 5000);
2.what is the main diffrence between thread and handler? i understood that the handler
run on the thread i call him from it (share with main thread cpu time), its currect?
- it look like i have access to class local variables from handler. but in thread, the eclipse let me write local class variables in thread but when it starts the address of this locals is not as the thread locals and i dont hava access to this class locals when thread run.
thank you!!!
For the 1st option, it is forbidden to access views such as mapView or any UI component from another thread other than the UI thread, which is why the Thread version will fail.
For a delay, the 2nd option using the Handler is the better way to do it and does not fail because the Handler is declared on the UI thread, which brings an important point about Handlers – Handlers operate on the thread that they are created on, but that thread must be initialized as Looper thread, such as the UI thread.
It would also be great if you can post the exception for clarity.