从Web读取数据并使用intent服务显示文本

时间:2012-12-23 10:57:35

标签: android android-intent service

我想要一个示例从web读取数据并使用intent service读取textview。我读了这个http://www.vogella.com/articles/AndroidServices/article.html但是下载了文件...我希望将数据存储到字符串中以便在main activity中的另一个函数中使用。谢谢

public class DownloadService extends IntentService {

private int result = Activity.RESULT_CANCELED;
public String s = "";

public DownloadService() {
super("DownloadService");
}

// Will be called asynchronously be Android
@Override
protected void onHandleIntent(Intent intent) {
Uri data = intent.getData();
String urlPath = intent.getStringExtra("urlpath");

InputStream stream = null;
//FileOutputStream fos = null;
try {

  URL url = new URL(urlPath);
  stream = url.openConnection().getInputStream();
  InputStreamReader reader = new InputStreamReader(stream);
  //fos = new FileOutputStream(output.getPath());
  int next = -1;

  while ((next = reader.read()) != -1) {
    //fos.write(next);
    s=s+next;
  }
  // Sucessful finished
  result = Activity.RESULT_OK;

1 个答案:

答案 0 :(得分:0)

您已将urlPath的inputStream附加到“s”

您可以使用::

从MainActivity访问“s”
String data=new DownloadService().s;

只是实例化IntentService并在实例化对象的句点帮助下访问它的参数。