持续运行后台服务以从URL获取数据

时间:2015-01-15 12:31:10

标签: android android-service

  • 在我的应用中,我有从URL获取数据,我想写一个简单的服务,它持续运行背景&给我通知....

1 个答案:

答案 0 :(得分:0)

如果你问的是如何在后台获取数据,而主线程不应该等待获取数据,那么你可以查看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);
    }
  }