2013-03-16 100 views
2

我有一個應用程序每隔一分鐘檢查一個特定的網站,看它是否找到我正在尋找的任何東西,然後在找到該項目時通知我(Plays Sound)。我跟着這個嘖嘖,讓我的應用程序在後臺運行,但我注意到它抱怨WebView。WebView可以在服務中使用嗎?

http://marakana.com/forums/android/examples/60.html

如果這是不可能使用一個服務裏面的WebView,我有哪些替代品達到同樣的目的?

謝謝!

+1

爲什麼你甚至*有一個'WebView'? 「WebView」扮演什麼角色? – CommonsWare 2013-03-16 22:13:05

回答

0

不,一個WebView不應該在服務內部使用,它確實沒有任何意義,無論如何。如果你加載你的WebView與刮包含的HTML的意圖,你可能也只是運行一個HTTPGET請求,這樣的 -

public static String readFromUrl(String url) { 
    String result = null; 

    HttpClient client = new DefaultHttpClient(); 

    HttpGet get = new HttpGet(url); 

    HttpResponse response; 
    try { 
     response = client.execute(get); 
     HttpEntity entity = response.getEntity(); 
     if (entity != null) { 
      InputStream is = entity.getContent(); 
      BufferedReader reader = new BufferedReader(
             new InputStreamReader(is)); 
      StringBuilder sb = new StringBuilder(); 

      String line = null; 
      try { 
       while((line = reader.readLine()) != null) 
        sb.append(line + "\n"); 
      } catch (IOException e) { 
       Log.e("readFromUrl", e.getMessage()); 
      } finally { 
       try { 
        is.close(); 
       } catch (IOException e) { 
        Log.e("readFromUrl", e.getMessage()); 
       } 
      } 

      result = sb.toString(); 
      is.close(); 
     } 


    } catch(Exception e) { 
     Log.e("readFromUrl", e.getMessage()); 
    } 

    return result; 
} 
+2

「一個WebView不能在服務中使用」 - 實際上,這不是真的,儘管在這種情況下,您的解決方案是最合適的,最有可能的。儘管我會推薦'Log.e()'而不是'printStackTrace()',Google建議通過HttpClient的'HttpUrlConnection'。 – CommonsWare 2013-03-16 22:27:48

+0

@CommonsWare,將我的「can」改爲「should」並替換Log.e.我知道Google對HttpUrlConnection的偏好,但爲了清楚起見,我更喜歡HttpClient。舊習慣。 – 323go 2013-03-16 22:36:38

1

是,服務在後臺運行,不應該能夠顯示任何用戶界面。

但是,您可以使用PendingIntent.getService(上下文,GET_ADSERVICE_REQUEST_CODE,...)將活動(UI進程)的上下文傳遞給服務。然後,當服務準備好顯示時,下面的行應該啓動瀏覽器(或者您擁有適用於自己的WebView的Intent過濾器的應用程序)來顯示Web內容。

  Intent i = new Intent(Intent.ACTION_VIEW, url); 
      PendingIntent contentIntent = PendingIntent.getActivity(this, 0, i, 
        Intent.FLAG_ACTIVITY_NEW_TASK); 
相關問題