2011-04-15 82 views
1

我有一个应用程序,登录到web服务,也上传文件。 我需要保持会话活着,我去不同的屏幕上,并从Web服务获取数据。 我读了我需要使http调用作为服务,也许启动我的应用程序的服务。 如何在http服务活动中将“登录”活动和“上传”活动httpclient调用?Android - httpclient作为后台服务

谢谢。

回答

6

由于服务与UI线程在同一线程上运行,因此您需要在不同的线程中运行该服务。线程但更清洁的另一种形式,如果你需要做的 - 在onCreate()方法中

  1. 使用该服务的onCreate()onBind()等方法中常用的Java线程
  2. 使用的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);   
    } 

然后,你必须扩展IntentService类并实现onHandleIntent(Intent intent)方法中的所有HTTP调用BackgroundConnectionService内。这是因为这个例子一样简单:

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); 
    } 
} 

最后,声明异步服务,你会在AndroidManifest.xml任何正常服务<application>标签内提交。

... 
     <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

+0

感谢您的提示。由于我是java新手,如果发布示例/代码段,这意味着很多。 – Codes12 2011-04-17 01:58:15

+0

进行编辑,详细说明如何使其工作。 – 2011-04-17 04:15:06

+0

非常感谢。我会尝试。 – Codes12 2011-04-18 17:04:00