Android-使用httpclient作为后台服务

| 我有一个登录Web服务并上传文件的应用程序。 我需要保持会话状态,因为我要转到不同的屏幕并从Web服务获取数据。 我读到我需要将http调用作为服务,并可能使用该服务启动我的应用程序。 如何将我的“登录”活动和“上载”活动httpclient调用放在http服务活动中? 谢谢。     
已邀请:
由于服务与UI线程在同一线程上运行,因此您需要在其他线程中运行该服务。您可以通过几种不同的方式执行此操作: 在服务的
onCreate ()
onBind()
等方法中使用常规的Java线程 在
onCreate()
方法中使用AsyncTask-另一种线程形式,但是如果需要进行UI更新,则更加简洁 使用提供异步服务任务执行的
IntentService
-不知道它的工作方式如何,因为我从未使用过它。 这三种方法都应允许您在后台通过Service与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);         
    }
然后在
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);
    }
}
最后,像在
<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>
...
那应该做。其实很简单:D     

要回复问题请先登录注册