Android - httpclient作为后台服务

Cod*_*s12 1 service android httpclient

我有一个登录Web服务的应用程序,也上传文件.当我进入不同的屏幕并从webservice获取数据时,我需要保持会话处于活动状态.我读过我需要将http调用作为服务,并且可能使用该服务启动我的应用程序.如何将我的"登录"活动和"上传"活动httpclient调用放在http服务活动中?

谢谢.

Sha*_*yay 6

由于服务在与UI线程相同的线程上运行,因此您需要在不同的线程中运行该服务.您可以通过以下几种方式执行此操作:

  1. 在服务onCreate ()onBind()等等方法中使用常规java线程
  2. onCreate()方法中使用AsyncTask - 另一种形式的线程,但如果需要进行UI更新则要更加清晰
  3. 用于IntentService提供异步服务任务执行的用途- 不确定它的工作原理,因为我从未使用它.

所有这三种方法都应该允许你在后台和服务中与HttpClient建立连接,即使我从未使用过IntentService,它看起来对我来说是最好的选择.如果您需要对UI进行更改(只能在UI线程上完成),AsyncTask将非常有用.

按请求编辑:所以我目前正在做一些以异步方式需要Http连接的东西.在发表这篇文章之后,我尝试了3号,它确实很好/很容易.唯一的问题是信息必须通过意图在两个上下文之间传递,这真的很难看.所以这里是一个近似的例子,你可以做一些事情来在异步的后台服务中建立http连接.

从外部活动启动异步服务.我只放了两个按钮,以便在服务运行时看到活动正在执行.意图可以在您想要的任何地方发布.

/* 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);         
    }
Run Code Online (Sandbox Code Playgroud)

然后,BackgroundConnectionService您必须扩展IntentService类并在该onHandleIntent(Intent intent)方法中实现所有http调用.它就像这个例子一样简单:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

最后,声明异步服务,就像<application>标记中AndroidManifest.xml文件中的任何普通服务一样.

...
        <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>
...
Run Code Online (Sandbox Code Playgroud)

应该这样做.实际上很简单:D