2012-12-23 64 views
0

我想一個例子,從網絡和拿出來與意圖的TextView中讀取數據service.I閱讀本http://www.vogella.com/articles/AndroidServices/article.html,但下載的文件......我想將數據存儲到字符串中的另一個用途在主要activity.Thanks功能。讀取數據

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; 
+0

你還嘗試過什麼嗎? –

+0

是...將此代碼轉換爲字符串...但我如何將它傳遞給主要活動? – user1909897

+0

我的問題是我如何從意向服務發送數據到主要活動。 – user1909897

回答

0

如您有追加從urlPath你的InputStream 「S」

您可以從您的MainActivity使用::

String data=new DownloadService().s; 

只是實例IntentService和訪問它的參數訪問您的 「S」在實例化對象的幫助下。