2011-04-15 57 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