I use AsyncTask to perform some data load over http requests in background. The http request use a session variable. This variable can become invalid and the http request will return an error.
In this case the user have to relogin.
So, can I just use something like this:
protected void onPostExecute(IData data) {
//
// !!On Error data object is null!!
//
if (mCallback != null) {
mCallback.onTaskComplete(data);
}
}
And in the Activity which implements the Callback interface I just check if the data object is null and change the Activity to the “MainActivity” Login form.
public void onTaskComplete(IData data) {
if (data == null) {
Intent intent = new Intent(ReadDataActivity.this, MainActivity.class);
deleteCurrentSavedSession();
startActivity(intent);
} else {
// Do something with the data
}
}
Is this a bad idea? Should I better use ExecutorService and execute it as a “normal” thread which checks if the session is still valid?
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.execute(sessionCheckWorker);
executor.shutdown();
while (!executor.isTerminated()) {
}
// Wait until session check task is finished and decide which Activity to load
Best Regards
Go for ExecutorService. It is meant specifically for such timer related tasks. I would also suggest you to use handlers in combination with ExecutorService, since handlers give you more control over such tasks as compared to Asynctask.