我有一个应用程序每隔一分钟检查一个特定的网站,看它是否找到我正在寻找的任何东西,然后在找到该项目时通知我(Plays Sound)。我跟着这个啧啧,让我的应用程序在后台运行,但我注意到它抱怨WebView。WebView可以在服务中使用吗?
http://marakana.com/forums/android/examples/60.html
如果这是不可能使用一个服务里面的WebView,我有哪些替代品达到同样的目的?
谢谢!
我有一个应用程序每隔一分钟检查一个特定的网站,看它是否找到我正在寻找的任何东西,然后在找到该项目时通知我(Plays Sound)。我跟着这个啧啧,让我的应用程序在后台运行,但我注意到它抱怨WebView。WebView可以在服务中使用吗?
http://marakana.com/forums/android/examples/60.html
如果这是不可能使用一个服务里面的WebView,我有哪些替代品达到同样的目的?
谢谢!
不,一个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;
}
“一个WebView不能在服务中使用” - 实际上,这不是真的,尽管在这种情况下,您的解决方案是最合适的,最有可能的。尽管我会推荐'Log.e()'而不是'printStackTrace()',Google建议通过HttpClient的'HttpUrlConnection'。 – CommonsWare 2013-03-16 22:27:48
@CommonsWare,将我的“can”改为“should”并替换Log.e.我知道Google对HttpUrlConnection的偏好,但为了清楚起见,我更喜欢HttpClient。旧习惯。 – 323go 2013-03-16 22:36:38
是,服务在后台运行,不应该能够显示任何用户界面。
但是,您可以使用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);
为什么你甚至*有一个'WebView'? “WebView”扮演什么角色? – CommonsWare 2013-03-16 22:13:05