问题
I have an app that checks a specific website every one minute to see if it finds whatever I am looking for, then notifies me (Plays Sound) whenever the item is found. I followed this tut to make my app run in the background, but I noticed it complains about the WebView.
http://marakana.com/forums/android/examples/60.html
If it's not possible to use a WebView inside a service, what are my alternatives to achieve the same goal?
Thank you!
回答1:
No, a WebView should not be used inside a service, and it really doesn't make sense to, anyway. If you're loading your WebView with the intention of scraping the html contained in it, you might as well just run an HttpGet request, like this --
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:
Yes, a service runs in the background and should not able able to display any UI.
But you can have an Activity (a UI process) passed its context to a service using PendingIntent.getService(context, GET_ADSERVICE_REQUEST_CODE, ...). Then when the service is ready to display, the lines below should launch browser (or you owner app with appropriate Intent Filter for own WebView) to display the web content.
Intent i = new Intent(Intent.ACTION_VIEW, url);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, i,
Intent.FLAG_ACTIVITY_NEW_TASK);
来源:https://stackoverflow.com/questions/15455129/can-webview-be-used-inside-a-service