I would suggest the use of publishProgress
to publish the current progress and override onProgressUpdate
which is executed on the main thread. With that, you won't have to use handlers and Threads in the AsyncTask
at all.
Notice that the first line has changed from extends AsyncTask<String, Void, Integer>
to extends AsyncTask<String, String, Integer>
. The middle parameter determines the object type of the Update Parameter. If you need to send complex data to the update method, change it to a class containing all information necessary.
class SendsequenceofRequest extends AsyncTask<String, String, Integer> {
@Override
protected Integer doInBackground(String... arg0) {
try {
// This will run indefinitely, unless stopped by break. So make sure you have an exit condition, see below
String response_req_sequence = null;
do {
response_req_sequence = SimpleHttpClient.sendresponseSequReqRes(response_send_order);
if(response_req_sequence != null) {
// Instead of calling runOnUiThread, call progress update
publishProgress(response_req_sequence);
}
// Wait before retry
Thread.sleep(3000);
// Keep in mind, that if the connection is successful, the string may be empty,
// so TextUtils.isEmpty(response_req_sequence); may be better exit condition as it checks if string is null or has size of 0
} while(response_req_sequence!=null);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
void onProgressUpdate(String... string) {
// This will always be executed in main thread
onPause();
Toast.makeText(getApplicationContext(), "Your Order will be delivered in"+response_req_sequence, 10000).show();
}
protected void onPostExecute(Integer feed) {
// Notify user the task has bene completed
Toast.makeText(getApplicationContext(), "Task completed.", 10000).show();
}
}