Issue
My application has a feature where it sends some data to a web service when an option is selected in a menu. To do this, I have an Activity that executes an AsyncTask once the item is selected.
Here is some sample code simplified to reduce complexity for demonstration purposes. The sendDataToWebService() method gets called on the selection event:
private void sendDataToWebService(MyData myData)
{
MyAsyncTask task = new MyAsyncTask();
task.execute(myData);
}
private class MyAsyncTask extends AsyncTask<MyData, Integer, String>
{
@Override
protected String doInBackground(MyData... myDataObjects)
{
// code here calls the data access layer, passing my data to it.
// The data access layer basically does this (simplyfied for this example):
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPostRequest = new HttpPost(uri);
response = httpclient.execute(httpPostRequest);
//... clean up and return response back to doInBackground()...
return someStringText;
}
@Override
protected void onPostExecute(String value)
{
// Do something related to the value parameter
}
}
I'm trying to account for the situation where the user starts sending the data to the web service but then receives an incoming phone call during transmission. When the incoming call event occurs, the activity's onPause method is called but because my transmission is happening in an AsyncTask, the AsyncTask thread is going to continue even after onPause has completed.
So I'm wondering what's the best way to handle this situation? Do I let it the AsyncTask continue to run? Do I listen for the incoming call event and try to cancel the AsyncTask?
How does the radio being used for transmitting (WiFi or cell network) affect this? I believe some carriers (e.g. Verizon) don't allow data transmissions over their cell network during a phone conversation. Is WiFi somehow affected by phone calls?
Would migrating this to a thread within a Service component make a difference?
Solution
As usual, it depends. How critical is the data? How big? Can you just retry if the transmission is interrupted? A phone call is not a special case. Your activity may be backgrounded at any time (user pressing the home button, etc.), and since this is a mobile device, you can lose connectivity at any time (train goes into tunnel, etc.)
You can just let it run, and if the data size is small, chances are it will be successfully uploaded. If it is bigger, a service will give you a better chance of finishing the upload, but it too may be restated, so you should handle this properly. You can also listen for connectivity changes (use a broadcast listener), and retry the upload automatically when the network is available.
Answered By - Nikolay Elenkov
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.