WebView可以在服务内部使用吗?

Amm*_*mar 5 android android-service android-webview

我有一个应用程序,它每隔一分钟检查一个特定网站,看看它是否找到我要查找的内容,然后在找到该项目时通知我(播放声音)。我按照这个方法让我的应用程序在后台运行,但我注意到它抱怨 WebView。

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

如果无法在服务中使用 WebView,我有哪些替代方案可以实现相同的目标?

323*_*3go -1

不, aWebView不应该在服务内部使用,而且无论如何它确实没有意义。如果您加载的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;
}
Run Code Online (Sandbox Code Playgroud)

  • “WebView 不能在服务内部使用”——实际上,这并不完全正确,尽管在这种情况下,您的解决方案很可能是合适的。尽管我会推荐使用“Log.e()”而不是“printStackTrace()”,并且 Google 推荐使用“HttpUrlConnection”而不是 HttpClient。 (3认同)