Reputation: 83
can any one please tell me how to make this code work in the background and what is the difference when i make the code work in the background as in "do in background" and a service and which approach should i take
thanks to all in advance
this is the code:
public void SticketFunction(double book, double libadd, long time){
Log.v("log_tag", "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SticketFunction()");
//HttpClient
HttpClient nnSticket = new DefaultHttpClient();
//Response handler
ResponseHandler<String> res = new BasicResponseHandler();
HttpPost postMethod = new HttpPost("http://www.books-something.com");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
nameValuePairs.add(new BasicNameValuePair("book", book+""));
nameValuePairs.add(new BasicNameValuePair("libAss", libass+""));
nameValuePairs.add(new BasicNameValuePair("Time", time+""));
nameValuePairs.add(new BasicNameValuePair("name", "jack"));
//Encode and set entity
postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
//Execute
//manSticket.execute(postMethod);
String response =Sticket.execute(postMethod, res).replaceAll("<(.|\n)*?>","");
if (response.equals("Done")){
//Log.v("log_tag", "!!!!!!!!!!!!!!!!!! SticketFunction got a DONE!");
}
else Log.v("log_tag", "!!!!!!!?????????? SticketFunction Bad or no response: " + response);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
//Log.v("log_tag", "???????????????????? SticketFunction Client Exception");
} catch (IOException e) {
// TODO Auto-generated catch block
//Log.v("log_tag", "???????????????????? IO Exception");
}
}
}
Upvotes: 0
Views: 2230
Reputation: 25584
The benefit of running a task in a Service
is that it is not destroyed if the user backs out of the calling Activity
.
You could look into extending IntentService and implementing onHandleIntent, which automatically does work on a separate thread.
When using a Service
(or IntentService
)in this situation, you would pass the NameValuePair
values in a Bundle. You would also need to save the Response
data to persistent storage (database, preferences, etc), for later retrieval in an Activity
.
Alternatively, you can run an AsyncTask in a regular Service
(implementing onStartCommand
), or in the calling Activity
.
Upvotes: 1