If I want to update my UI from a background thread when a message is received from a web service call, would the below be considered a safe option? I'm worried about potential memory leaks having the handler in my Application class
public class MyApplication extends Application {
private static long uiThreadId;
private static Handler uiHandler;
@Override
public void onCreate() {
super.onCreate();
uiThreadId = Thread.currentThread().getId();
uiHandler = new Handler();
}
public static void customRunOnUiThread(Runnable action) {
if (Thread.currentThread().getId() != uiThreadId) {
uiHandler.post(action);
} else {
action.run();
}
} }
And then in the class that deals with the messages received in the separate threads:
new Thread(
new Runnable() {
@Override
public void run() {
// make web service call
MyApplication.customRunOnUiThread(new Runnable() {
@Override
public void run() {
httpResponseHandler.onSuccess();
}
});
}
}
}).start();
My alternative is to use parallel AsyncTasks doing the work in the doInBackground method and updating the UI in the onPostExecute method. Both of these options work, but I'm not sure which one is 'most' correct so to speak.