Is the following a safe thing to do. It sure is handy, but can the Handler get garbage collected before the runnable runs?
public void dodelayed()
{
new Handler().postDelayed(new Runnable() {
@Override
public void run()
{
//do something
}
}, 50);
}
No, it is not GCed. It is just fine to do it this way.
Little longer explanation, to avoid confusions:
Although you don't store the reference to the handler, it is stored somewhere else. In the method sendMessageAtTime, which is called from inside postDelayed
, before the handler puts the message in the message queue, it assigns itself in the target
field of the message, so there is still a reference to the Handler, and it is not GCed:
public boolean sendMessageAtTime(Message msg, long uptimeMillis)
{
//...
if (queue != null)
{
msg.target = this; // here the reference to the handler is assigned
sent = queue.enqueueMessage(msg, uptimeMillis);
}
//...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With