What is the less memory consuming and fastest (in respect of code lines and time of execution) way to do some task in the background thread?
I need to send many simple tasks to the background thread and I won’t obviously use AsyncTask class for this. So is handler what I am looking for or there’s a faster way?
final Handler handler = new Handler();
final Runnable runnable = new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
handler.post(new Runnable() {
@Override
public void run() {
infoMsg.setVisibility(View.INVISIBLE);
}
});
}
};
new Thread(runnable).start();
handler is usually used for the UI thread in order to postpone something to be done in the future.
in your example , this solution would be perfect.
asynctask is used when you don’t care for when and what should be the order of the tasks to do . asynctasks should not be used for too long operations (like a connection that keeps being alive till the end user stops it) . you cannot assume that at more than one asynctask are active (but one is ok to assume) .
for any other usage , i simply use a thread , but mostly the handler and the asynctask are enough.