Since a service runs on the same thread as the UI thread, you will need to run the service in a different thread. You can do this in several different ways:
- Use regular java threading within the service's
onCreate ()
or onBind()
etc, methods
- Use AsyncTask within the
onCreate()
method - another form of threading but much cleaner if you need to do UI updates
- Use
IntentService
which provides asynchronous Service task execution - not sure how well this works as I have never used it.
All three of these methods should allow you to make connections with the HttpClient in the background and through a Service and even though I have never used IntentService, it looks like the best option to me. AsyncTask would be very useful if you need to make changes to the UI which can only be done on the UI thread.
Edit by request: So I am currently doing something which requires Http connections in a asynchronous way. After making this post, I tried doing number 3 and it does work very well/easily. The only problem is that information has to be passed between two contexts through intents which is really ugly. So here is an approximate example of something you can do to make http connections in an asynchronous, background, service.
Launch the asynchronous service from an outside activity. I put two buttons just so the activity can be seen executing while the service is running. The intent can be launched really anywhere you feel like.
/* Can be executed when button is clicked, activity is launched, etc.
Here I launch it from a OnClickListener of a button. Not really relevant to our interests. */
public void onClick(View v) {
Intent i = new Intent ("com.test.services.BackgroundConnectionService");
v.getContext().startService(i);
}
Then within the BackgroundConnectionService
you have to extend the IntentService class and implement all http calls within the onHandleIntent(Intent intent)
method. It is as easy as this example:
public class BackgroundConnectionService extends IntentService {
public BackgroundConnectionService() {
// Need this to name the service
super ("ConnectionServices");
}
@Override
protected void onHandleIntent(Intent arg0) {
// Do stuff that you want to happen asynchronously here
DefaultHttpClient httpclient = new DefaultHttpClient ();
HttpGet httpget = new HttpGet ("http://www.google.com");
// Some try and catch that I am leaving out
httpclient.execute (httpget);
}
}
Finally, declare the asynchronous service as you would any normal service in the AndroidManifest.xml file within the <application>
tags.
...
<service android:name="com.test.services.BackgroundConnectionService">
<intent-filter>
<action android:name="com.test.services.BackgroundConnectionService" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</service>
...
That should about do it. It is actually pretty easy : D
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…