1

我想要一个示例从网络读取数据并通过意图服务输出到 textview。我阅读了这个http://www.vogella.com/articles/AndroidServices/article.html但下载文件...我想将数据存储为字符串在主要活动的另一个功能中使用。谢谢。

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;
4

1 回答 1

0

由于您已将 inputStream 从 urlPath 附加到“s”

您可以使用以下方法从 MainActivity 访问您的“s”:

String data=new DownloadService().s;

只需实例化 IntentService 并借助实例化对象上的句点访问它的参数。

于 2012-12-29T15:27:11.667 回答