运行 持续从 url 获取数据的后台服务
running background service continuously for getting data from url
- 在我的应用程序中,我从 URL 获取数据,我想编写一个简单的服务,持续 运行 后台并给我通知....
如果您的问题是如何在后台从 url 获取数据,而主线程不应等待获取数据,那么您可以查看 Asynctask 来实现这一点。下面的代码示例:
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
@Override
protected void onPostExecute(String result) {
textView.setText(result);
}
}
- 在我的应用程序中,我从 URL 获取数据,我想编写一个简单的服务,持续 运行 后台并给我通知....
如果您的问题是如何在后台从 url 获取数据,而主线程不应等待获取数据,那么您可以查看 Asynctask 来实现这一点。下面的代码示例:
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
@Override
protected void onPostExecute(String result) {
textView.setText(result);
}
}