2

I have an android app that makes a httpget request using an asynctask, now while the request is in process, if i get a call or internet connectivity is lost somehow, the app crashes. I think using a broadcast receiver to check on network state would be the best. Could anyone suggest the right thing to do?

Linus Kleen
  • 33,871
  • 11
  • 91
  • 99
  • 2
    I think this answers your question: http://stackoverflow.com/questions/6039158/android-cancel-async-task?rq=1 – ılǝ Nov 19 '12 at 05:38
  • @ile: the question is how to handle asynctask while incoming call or data lost. It is crashing so he dont need to cancel any tasks in already crashed application. Anmol Gagneja: Your question title should be changed totally i guess. – Kartihkraj Duraisamy Nov 19 '12 at 07:01
  • Edit the title to : Handling Incoming call or any n/w failure during asynctask. this could be sounds better for your question. – Kartihkraj Duraisamy Nov 19 '12 at 07:07

1 Answers1

0

If your problem is app crashing, and you dont want your app to be crashed

then make the server communication inside try catch . So that if any unexpected failure or incoming call interruption your app will not crash.

The result may be anyone of the following,

while receiving incoming calls,

  1. If the communication completed, then it will show you the result what you expects after the task.

  2. If communication failed to server, then the app will remain the old state or screen that before you called asynctask.

If you are worrying about to handle this task failure,

then you can return your catch result to onPostExecute() and do Something what you wish to do after these type of failures.

Probably registering a broadcastreceiver is not a good idea with the background thread.

because anyway if such situations arises , you dont need to cancel the AsyncTask, it will be automatically cancelled.

And another one problem is, if you register an receiver it will be fired whenever your application alive and an incoming call happens even if you are not communication with web server.

Firing broadcast receivers will drain the battery.

Still if need to register a receiver, then the following link tells you everything and sample code about the connectivity receiver,

Detect Connection Changes receiver

Note, register a receiver in oncreate() and unregister in onDestroy() is lightweight and elegant one than registering a receiver in .

Additional info:

If you need to cancel your asynctask in sometime, then the following link could be a useful one

Ideal way to cancel an executing AsyncTask

Community
  • 1
  • 1
Kartihkraj Duraisamy
  • 3,171
  • 2
  • 25
  • 36