2013-01-14 22 views
0

我正在開發一個登錄到tomcat服務器的應用程序。 我正在使用HTTP GET請求來執行此操作,並且在成功連接後,將通過緩衝流顯示消息 。ANDROID - 活動更改時連接不停留

以下代碼用於連接。

public String getInternetData() throws Exception { 


BufferedReader in = null; 
String data = null; 

try { 
    HttpClient client = new DefaultHttpClient(); 
    client.getConnectionManager().getSchemeRegistry().register(getMockedScheme()); 
    URI website = new URI("https://ts.rks.com:8443/kss/login?username=hydm&password=pw1234"); 
    HttpGet request = new HttpGet(); 
    request.setURI(website); 
    HttpResponse response = client.execute(request); 
    response.getStatusLine().getStatusCode(); 

    in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); 
    StringBuffer sb = new StringBuffer(""); 
    String l = ""; 
    String nl = System.getProperty("line.separator"); 
    while ((l = in.readLine()) != null) { 
     sb.append(l + nl); 
    } 
    in.close(); 
    data = sb.toString(); 
    return data; 
} finally { 
    if (in != null) { 
     try { 
      in.close(); 
      return data; 
     } catch (Exception e) { 
      Log.e("GetMethodLogin", e.getMessage()); 
     } 
    } 
} 

這是用戶通過登錄活動登錄時激活的代碼。 當我回到菜單屏幕並嘗試運行需要用戶 登錄的其他活動時,它表示用戶未登錄。

當用戶離開時連接斷開該活動還是我沒有正確建立連接。

回答

0

其實有你需要改變兩件事情,不只是一個。

任何你需要持續存在的活動應該在服務中完成,而不是在活動的代碼中完成。其次,在最近的Android發行版中,所有網絡必須由後臺線程完成,而不是UI線程(總是有針對UI線程聯網的建議,但現在觸發異常)。將代碼放入服務並不意味着它在另一個線程中。

所以答案是,你應該使用後臺線程機制之一來做這件事,並且在服務中這樣做。

0

當活動移動到後臺時,連接不會持續。我無法從您的發佈代碼中知道,但我相信您應該使用AsyncTask進行此連接。這來自我從鏈接中拉取HTML源碼的經驗。

這個問題可以回答你:What to do with AsyncTask in onPause()?