所以我的服务中有这个代码。
public void longPolling(String url) {
HttpURLConnection connection = null;
BufferedReader rd = null;
StringBuilder sb = null;
String line = null;
URL serverAddress = null;
String lastModify = null;
String etag = null;
while (true) {
try {
serverAddress = new URL(url);
// set up out communications stuff
connection = null;
// Set up the initial connection
connection = (HttpURLConnection) serverAddress.openConnection();
connection.setRequestMethod("GET");
// connection.setDoOutput(true);
connection.setReadTimeout(60000);
if (lastModify != null) {
connection.setRequestProperty("If-Modified-Since",
lastModify);
}
if (etag != null) {
connection.setRequestProperty("If-None-Match", etag);
}
connection.connect();
// read the result from the server
rd = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
sb = new StringBuilder();
while ((line = rd.readLine()) != null) {
sb.append(line + '\n');
}
lastModify = connection.getHeaderField("Last-Modified");
etag = connection.getHeaderField("Etag");
String response = java.net.URLDecoder.decode(sb.toString(),
"UTF-8");
sendResults(response); //sends broadcast to activities.
} catch (MalformedURLException e) {
log.debug(e);
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
log.debug(e);
} catch (IOException e) {
e.printStackTrace();
log.debug(e);
} catch (Exception e) {
e.printStackTrace();
log.debug(e);
} finally { // close the connection, set all objects to null
connection.disconnect();
rd = null;
sb = null;
connection = null;
}
}
}
工作正常。但是当用户退出应用程序时,应该停止服务。但这次民意调查并未停止。即使服务停止,它也会继续运行。
答案 0 :(得分:0)
因为你写while(true)创建一个变量并声明最初为true并在服务的onstop()方法中设置为false并将该变量设置为while(你的变量)即...