AsynTask cancel long running operation like HttpGet - android

I've seen several other post about canceling an AsynTask, but I don't think any of them resolves the issues. Imagine this scenario:
public class TestTask extends AsyncTask<Void, Void, Object> {
#Override
protected void onCancelled(Object result) {
running = false;
Log.i("Test", "onCancelled");
}
#Override
protected Object doInBackground(Void... params) {
try {
Log.i("Test", "cancelling");
cancel(true);
Thread.sleep(5000);
Log.i("Test", "Past sleep");
} catch (InterruptedException e) {
Log.i("Test", "InterruptedException", e);
}
return null;
}
}
Imagine I'd like to cancel this long 20 second request in the middle of a download, for example if the server is responding slow to a json request. So the Thread.sleep(5000) could be a HttpGet request that I'd like to cancel. However the cancel method is marked as final so I can't override it and call get.abort(). The onCancel hook happens after the doInBackground and back on the UI thread. Checking for isCancel won't do me any good once the HttpGet request has started.
The way I solve this is to make an abort() method on my AsynTask and just call that.
public void abort() {
get.abort();
cancel(true);
}
but this seems to go against the Android grain a bit. Is there a better way to cancel the request?

In the docs for HttpGet, there is no mention of thread safety, so calling abort() the way you described will probably lead to undesired results (at best). What you could do is pass an HttpGet object in the constructor for your AsyncTask, or via a setter (as long you do this before you call AsyncTask.execute()).
You would have to check periodically inside of doInBackground() if the task has been cancelled:
#Override
protected Object doInBackground(Void... params) {
// start GET request
try {
Log.i("Test", "cancelling");
cancel(true);
Thread.sleep(5000);
Log.i("Test", "Past sleep");
if ( this.isCancelled() ) {
// abort GET request and/or stop doing other work
return null;
}
else {
// do what ever work you need to
}
} catch (InterruptedException e) {
Log.i("Test", "InterruptedException", e);
}
return null;
}
Source.
You can always call AsyncTask.cancel(true) whenever you feel the task should be stopped (AsyncTask.cancel())

I am not sure if this is applicable or not, but you could create another thread using an executor service that executes the download-task and keep checking for isCancelled() inside doInBackground() or until the future object returns, whichever happens first:
#Override
protected Object doInBackground(Void... params)
{
Callable<Void> downlaodTask = new Callable<Void>()
{
#Override
public Void call() throws Exception
{
// download task here
return null;
}
};
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Void> future = executor.submit(downlaodTask);
while(true) // check every second
{
try
{
future.get(1, TimeUnit.SECONDS); // wait until the download task finishes with 1 second as a timeout
break;
}
catch(TimeoutException e)
{
if(isCancelled())
{
executor.shutdownNow(); // or abort() or both
break;
}
}
}
return null;
}

Related

AsyncTask doInBackground(); executing multiple methods one by one

I'm having trouble with AsyncTask running multiple methods in doInBackground. this is my AsyncTask code:
public class FETCHDATA extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
pdialog = new ProgressDialog(getContext());
pdialog.setTitle("Please Wait");
pdialog.setMessage("Fetching data...");
pdialog.show();
}
#Override
protected Void doInBackground(Void... voids) {
try{
method1();
method2();
method3();
method4();
method5();
method6();
method7();
}catch (Throwable e){
e.printStackTrace();
}
}
#Override
protected void onPostExecute(Void aVoid) {
if (pdialog.isShowing()){
pdialog.dismiss();
}
}
Instead running and waiting the first method is done, the doInBackground proceeds to the next method. and the ProgressDialog dismiss by one second.
Note
Every Method will get data from our API and save it on my SQLiteDatabase .
QUESTION
How can i execute my methods when the first method has finished getting and saving data before moving to the second methods.
Maybe you have to create multiples AsyncTask and whenever the first method finish, communicate it with returning a boolean instead of void instance here ---> extends AsyncTask.
This is weird.
I assume that your methodX() are asynchronous call?
In that case, you can use Thread.join() or CountDownLatch.
You are violating usage of async task. Async task is designed for doing short async operations and update the UI easily before, during and after, It is not for doing 7 network & Sqlite operations at once.
You can read more here, : https://developer.android.com/reference/android/os/AsyncTask
So you need to implement some kind of job for yourself to execute these operations at once or use some popular libraries like Retrofit.
If you insist to use async task, since an async task need to be executed from UI thread, you need to create new async task an execute it from onPostExecute every time when it is done and you of course need to pass a param(a counter or something) to doInBackground to know which method should be called.
You can put a counter with a switch case statment in the doInBackground in wich you choose the methode to execute and then in the onPostExecute call new FETCHDATA().execute() recursively
EDIT : working code ( i forgot break; after case;)
int counter = 1; // global
class Fetchdata extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... voids) {
try {
switch (counter) {
case 1:
method1();
break;
case 2:
method2();
break;
case 3:
method3();
break;
case 4:
method4();
break;
case 5:
method5();
break;
default:
cancel(true);
counter = 1;
break;
}
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
counter+=1;
Log.d(TAG, "onPostExecute: "+counter);
// cancel(true);
new Fetchdata().execute();
}
}
void method1(){
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.d(TAG, "methode1: coucou");
}
void method2(){
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.d(TAG, "methode2: ");
}
void method3(){
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.d(TAG, "methode3: ");
}
void method4(){
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.d(TAG, "methode4: ");
}
void method5(){
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.d(TAG, "methode5: ");
}
I think the problem is that your all methods or some methods already runs on a separate thread . So whenever you call a method which already runs on separate thread doInBackground() i.e current thread will not wait for it and continue the execution.
Apart from that The way you put try-catch is not a proper way to do it . Also if you want to call several threads one after another you should go with ThreadPoolExecuter.
If you are not using a Network library To make API calls you can use RetroFit.

AsyncTask onPostExecute not reached

I'm trying to execute this AsyncTask to connect to the server but it is stuck and doesn't reach onPostExecute().
class UnoConnection extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
IP = enterIP.getText().toString();
Response = "";
Log.i("Network", "Available");
}
#Override
protected Boolean doInBackground(Void... params) {
try {
InetAddress serverAddress = InetAddress.getByName(IP);
Log.i("Socket", "Trying to create...");
socket = new Socket();
socket.connect(new InetSocketAddress(serverAddress, 4444), 2000);
Log.i("Socket", "Created: " + socket.toString());
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
#Override
protected void onPostExecute(Boolean aBoolean) {
Log.i("Socket", "Post..." + aBoolean);
super.onPostExecute(aBoolean);
if (aBoolean) {
connect.setChecked(true);
showToast("Connected :)", "long");
enable(controls);
enterIP.setEnabled(false);
} else {
showToast("Unable to connect...!", "long");
connect.setChecked(false);
disable(controls);
enterIP.setEnabled(true);
}
Log.i("Socket", "Post..." + aBoolean);
}
}
The Method calling this AsyncTask is below:
switch (thisView.getId()) {
case R.id.connect:
UnoCon = new UnoConnection();
UnoCon.execute();
while (!(UnoCon.getStatus().equals(AsyncTask.Status.FINISHED))) {
Log.i("UnoCon",UnoCon.getStatus().toString());
}
if (socket == null) break;
cmdSend = new commandSender();
cmdSend.execute('2', 'R');
while (!(cmdSend.getStatus().equals(AsyncTask.Status.FINISHED))) {
Log.i("cmdSend", "Not Finished Yet");
}
if (commandSent) {
respRec = new responseReceiver();
respRec.execute();
while (!(respRec.getStatus().equals(AsyncTask.Status.FINISHED))) {
Log.i("respRec", "Not Finished Yet");
}
switch (Response) {
case "1":
Relay1.setChecked(true);
break;
case "0":
Relay1.setChecked(false);
break;
default:
break;
}
}
Log.i("Socket", socket.getInetAddress().toString());
break;
So when enabling the above //Log.i("UnoCon",UnoCon.getStatus().toString()); it always give running.
When I tried using some breakpoints I realized that it:
Enters doInBackground & does everything with no exception
return true then move to return false without even writing the stacktrace
jumps to AsyncTask class & then I don't know what happens
Maybe you called cancel() on your AsyncTask
See: http://developer.android.com/reference/android/os/AsyncTask.html#cancel(boolean)
the problem is this line:
while (!(UnoCon.getStatus().equals(AsyncTask.Status.FINISHED))) {
Log.i("UnoCon",UnoCon.getStatus().toString());
}
you start the stuff on the bakcgorund thread, but then you block the UI thread.
First that is completely wrong. Blocking the UI thread with a while loop waiting for something from the background thread is just as bad as doing the background work directly on the UI thread.
Then the reason onPostExecute doesn't execute is because this method is on the queue to be processed on the UI thread, but you're blocking the UI thread.
To fix it you have to remove this loop and find another way of processing whatever you're processing after the background thread finishes.

how to force the AsyncTask to wait

i want the AsyncTask to wait till it finishes. so i wrote the below code and i used .get() method as follows and as shown below in the code
mATDisableBT = new ATDisableBT();
but at run time the .get() doesnt force ATDisableBT to wait, becuase in the logcat i receive mixed order of messages issued from ATDisableBT and ATEnableBT
which means .get() on ATDisableBT did not force it to wait
how to force the AsyncTask to wait
code:
//preparatory step 1
if (this.mBTAdapter.isEnabled()) {
mATDisableBT = new ATDisableBT();
try {
mATDisableBT.execute().get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
//enable BT.
this.mATEnableBT = new ATEnableBT();
this.mATEnableBT.execute();
You can do this way:
doInBackground of AsyncTask
#Override
protected Void doInBackground(String... params) {
Log.i("doInBackground", "1");
synchronized (this) {
try {
mAsyncTask.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Log.i("doInBackground", "2");
return null;
}
Outside this function from where you have to nstrong textotify AsyncTask to release from wait state:
new CountDownTimer(2000, 2000) {
#Override
public void onTick(long l) {
}
#Override
public void onFinish() {
synchronized (mAsyncTask) {
mAsyncTask.notify();
}
}
}.start();
Here I have notified AsyncTask by CountDownTimer after 2 seconds.
Hope this will help you.
You should execute AsyncTask on UI thread, so using get() - which will block it makes no sense - it might get you ANR error.
If you are on HONEYCOMB and up, then AsyncTasks are executed on single executor thread, serially - so your mATEnableBT should get executed after mATDisableBT. For more see here:
http://developer.android.com/reference/android/os/AsyncTask.html#execute(Params...)
You might also switch from AsyncTask to Executors. AsyncTask is implemented using executors. By creating single threaded executor you make sure tasks will get executed serially:
ExecutorService executor = Executors.newSingleThreadExecutor();
//...
executor.submit(new Runnable() {
#Override
public void run() {
// your mATDisableBT code
}
});
executor.submit(new Runnable() {
#Override
public void run() {
// your mATEnableBT code
}
});

Android Timed Async Task

Hi currently i have the following code which utilizes Asycn Task and Timer.
My async task is basically trying to send a HTTP GET method from a URL where the response from the server could varies depending on connection and load.
What i would like to do is to have a timed async task. Where, it will schedule an AsyncTask every X second BUT if there is currently an Async Task in progress i would have to kill it first. Then start a new one.
Here is the code that i have at the moment:
private static boolean running = false;
Timer myTimer;
protected void onCreate(Bundle savedInstanceState) {
/* REST OF CODE OMITTED */
MyTimerTask myTask = new MyTimerTask();
myTimer = new Timer();
myTimer.schedule(myTask, 0, 10000);
}
/* REST OF CODE OMITTED */
private class MyTimerTask extends TimerTask {
public void run() {
if(!running){
Log.i("TAG", "NEW TIMER STARTED.");
RetrieveChatMessage task = new RetrieveChatMessage();
task.execute();
running = true;
}else{
running = false;
}
}
}
private class RetrieveChatMessage extends AsyncTask<String, Void, ArrayList<Chat>> {
#Override
protected ArrayList<Chat> doInBackground(String... params) {
// TODO Auto-generated method stub
ArrayList<Chat> cList = null;
String jResult = null;
Log.i("TAG", "RETRIEVING CHAT MESSAGE");
try {
jResult = ((new HttpRetriever())).getChatList(mAccount.email, mAccount.passwd);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if(jResult != null){
Log.i("TAG", "JSON DATA: " + jResult);
cList = (new ChatHandlers()).getChatList(jResult);
}else{
cList = null;
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("TAG", "JSON Exception " + e.toString());
}
return cList;
}
#Override
protected void onPostExecute(final ArrayList<Chat> result) {
Log.i("TAG", "ON POST EXECUTE");
if(result != null){
// Do something here
}
}
}
To be honest the code above works with slight issues:
1. It seems to execute the Async randomly, instead of every 10 seconds.
2. When i go to another activity, somewhat it prevents other Async task from doing its job (Which is also trying to retrieve JSON response from server).
I am not too worried about the later problem (and that is not the question i am asking). I just would like to know how to have a proper timed Async Task. Can anyone point me to a direction.
Thank you.
EDIT #1:
after reading #thepoosh comment's i tried the following (i put it in onCreate):
scheduleTaskExecutor= Executors.newScheduledThreadPool(5);
scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
public void run() {
// Parsing RSS feed:
// myFeedParser.doSomething();
Log.w("THUMBQOO", "NEW TASK STARTED");
retrieveChat();
}
}, 0, 15, TimeUnit.SECONDS);
Result: i have a consistent execution of Task. However, it seems that retrieveChat(); is never be called after the first execution.
Actually AsyncTask is not used for long operations .Check Here
You should use a Thread that uses a interface to notify UI or you can simply use a Handler which is the most Preffered way in android. Simply you can do a task repeatedly for every 10 seconds by
handler.postDelayed(new Runnable() {
#Override
public void run() {
// do work
handler.postDelayed(10000);
}
}, 10000);
Declare a Handler object to maintain future task executor...
private Handler mTimerHandler = new Handler();
Write a thread which will execute your future task...
private Runnable mTimerExecutor = new Runnable() {
#Override
public void run() {
//write your code what you want to do after the specified time elapsed
if(!running){
RetrieveChatMessage task = new RetrieveChatMessage();
task.execute();
running = true;
}else{
running = false;
}
}
};
Call your future tast executor with time using hanlder...
mTimerHandler.postDelayed(mTimerExecutor, 10000);
You can cancle your future task executor any time by this...
mTimerHandler.removeCallbacks(mTimerExecutor);
I am not sure if this is a very good way of accomplishing this (my answer here below) :
Use a Handler, create a HandlerThread and keep posting messages to this handler.
For the handlers "handleMessage" method, you can do your task and again send a message back to the MessageQueue.
HandlerThread thread = new HandlerThread(<name>);
thread.start();
Looper looper = thread.getLooper();
CustomHandler handler = new CustomHandler(looper);
// The CustomHandler class
class CustomHandler extends Handler {
public CustomHandler(Looper looper) {
super(looper);
}
#Override
public void handleMessage(Message msg) {
//Do your operation here
handler.sendEmptyMessageDelayed(msg, <delayTime>);
}
}

Ideal way to cancel an executing AsyncTask

I am running remote audio-file-fetching and audio file playback operations in a background thread using AsyncTask. A Cancellable progress bar is shown for the time the fetch operation runs.
I want to cancel/abort the AsyncTask run when the user cancels (decides against) the operation. What is the ideal way to handle such a case?
Just discovered that AlertDialogs's boolean cancel(...); I've been using everywhere actually does nothing. Great.
So...
public class MyTask extends AsyncTask<Void, Void, Void> {
private volatile boolean running = true;
private final ProgressDialog progressDialog;
public MyTask(Context ctx) {
progressDialog = gimmeOne(ctx);
progressDialog.setCancelable(true);
progressDialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
// actually could set running = false; right here, but I'll
// stick to contract.
cancel(true);
}
});
}
#Override
protected void onPreExecute() {
progressDialog.show();
}
#Override
protected void onCancelled() {
running = false;
}
#Override
protected Void doInBackground(Void... params) {
while (running) {
// does the hard work
}
return null;
}
// ...
}
If you're doing computations:
You have to check isCancelled() periodically.
If you're doing a HTTP request:
Save the instance of your HttpGet or HttpPost somewhere (eg. a public field).
After calling cancel, call request.abort(). This will cause IOException be thrown inside your doInBackground.
In my case, I had a connector class which I used in various AsyncTasks. To keep it simple, I added a new abortAllRequests method to that class and called this method directly after calling cancel.
The thing is that AsyncTask.cancel() call only calls the onCancel function in your task. This is where you want to handle the cancel request.
Here is a small task I use to trigger an update method
private class UpdateTask extends AsyncTask<Void, Void, Void> {
private boolean running = true;
#Override
protected void onCancelled() {
running = false;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
onUpdate();
}
#Override
protected Void doInBackground(Void... params) {
while(running) {
publishProgress();
}
return null;
}
}
Simple: don't use an AsyncTask. AsyncTask is designed for short operations that end quickly (tens of seconds) and therefore do not need to be canceled. "Audio file playback" does not qualify. You don't even need a background thread for ordinary audio file playback.
The only way to do it is by checking the value of the isCancelled() method and stopping playback when it returns true.
This is how I write my AsyncTask
the key point is add Thread.sleep(1);
#Override protected Integer doInBackground(String... params) {
Log.d(TAG, PRE + "url:" + params[0]);
Log.d(TAG, PRE + "file name:" + params[1]);
downloadPath = params[1];
int returnCode = SUCCESS;
FileOutputStream fos = null;
try {
URL url = new URL(params[0]);
File file = new File(params[1]);
fos = new FileOutputStream(file);
long startTime = System.currentTimeMillis();
URLConnection ucon = url.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
byte[] data = new byte[10240];
int nFinishSize = 0;
while( bis.read(data, 0, 10240) != -1){
fos.write(data, 0, 10240);
nFinishSize += 10240;
**Thread.sleep( 1 ); // this make cancel method work**
this.publishProgress(nFinishSize);
}
data = null;
Log.d(TAG, "download ready in"
+ ((System.currentTimeMillis() - startTime) / 1000)
+ " sec");
} catch (IOException e) {
Log.d(TAG, PRE + "Error: " + e);
returnCode = FAIL;
} catch (Exception e){
e.printStackTrace();
} finally{
try {
if(fos != null)
fos.close();
} catch (IOException e) {
Log.d(TAG, PRE + "Error: " + e);
e.printStackTrace();
}
}
return returnCode;
}
Our global AsyncTask class variable
LongOperation LongOperationOdeme = new LongOperation();
And KEYCODE_BACK action which interrupt AsyncTask
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
LongOperationOdeme.cancel(true);
}
return super.onKeyDown(keyCode, event);
}
It works for me.
I don't like to force interrupt my async tasks with cancel(true) unnecessarily because they may have resources to be freed, such as closing sockets or file streams, writing data to the local database etc. On the other hand, I have faced situations in which the async task refuses to finish itself part of the time, for example sometimes when the main activity is being closed and I request the async task to finish from inside the activity's onPause() method. So it's not a matter of simply calling running = false. I have to go for a mixed solution: both call running = false, then giving the async task a few milliseconds to finish, and then call either cancel(false) or cancel(true).
if (backgroundTask != null) {
backgroundTask.requestTermination();
try {
Thread.sleep((int)(0.5 * 1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
if (backgroundTask.getStatus() != AsyncTask.Status.FINISHED) {
backgroundTask.cancel(false);
}
backgroundTask = null;
}
As a side result, after doInBackground() finishes, sometimes the onCancelled() method is called, and sometimes onPostExecute(). But at least the async task termination is guaranteed.
With reference to Yanchenko's answer on 29 April '10:
Using a 'while(running)' approach is neat when your code under 'doInBackground' has to be executed multiple times during every execution of the AsyncTask. If your code under 'doInBackground' has to be executed only once per execution of the AsyncTask, wrapping all your code under 'doInBackground' in a 'while(running)' loop will not stop the background code (background thread) from running when the AsyncTask itself is cancelled, because the 'while(running)' condition will only be evaluated once all the code inside the while loop has been executed at least once. You should thus either
(a.) break up your code under 'doInBackground' into multiple 'while(running)' blocks or
(b.) perform numerous 'isCancelled' checks throughout your 'doInBackground' code, as explained under "Cancelling a task" at https://developer.android.com/reference/android/os/AsyncTask.html.
For option (a.) one can thus modify Yanchenko's answer as follows:
public class MyTask extends AsyncTask<Void, Void, Void> {
private volatile boolean running = true;
//...
#Override
protected void onCancelled() {
running = false;
}
#Override
protected Void doInBackground(Void... params) {
// does the hard work
while (running) {
// part 1 of the hard work
}
while (running) {
// part 2 of the hard work
}
// ...
while (running) {
// part x of the hard work
}
return null;
}
// ...
For option (b.) your code in 'doInBackground' will look something like this:
public class MyTask extends AsyncTask<Void, Void, Void> {
//...
#Override
protected Void doInBackground(Void... params) {
// part 1 of the hard work
// ...
if (isCancelled()) {return null;}
// part 2 of the hard work
// ...
if (isCancelled()) {return null;}
// ...
// part x of the hard work
// ...
if (isCancelled()) {return null;}
}
// ...

Categories

Resources