簡體   English   中英

使用android中的服務下載多個文件

[英]Download multiple files using a Service in android

我的應用程序有很多可以下載的可選數據,所以我決定使用一個服務來處理后台的所有下載,所以我開始學習它,這里是我得到的:

public class DownloadService extends IntentService{

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

    }

    @Override
    protected void onHandleIntent(Intent intent) {

        String URL=intent.getStringExtra("DownloadService_URL");
        String FileName=intent.getStringExtra("DownloadService_FILENAME");
        String Path=intent.getStringExtra("DownloadService_PATH");

        try{
        URL url = new URL(URL);
        URLConnection conexion = url.openConnection();

        conexion.connect();


        InputStream input = new BufferedInputStream(url.openStream());
        OutputStream output = new FileOutputStream(Path+FileName);

        byte data[] = new byte[1024];

        int count = 0;
        while ((count = input.read(data)) != -1) {
            output.write(data);
        }

        output.flush();
        output.close();
        input.close();

        }
        catch(Exception e){ }
    }

}

主要活動的代碼:

        Intent ServiceIntent = new Intent(this,DownloadService.class);
        ServiceIntent.putExtra("DownloadService_URL", "the url...");
        ServiceIntent.putExtra("DownloadService_FILENAME", "Test1.rar");
        ServiceIntent.putExtra("DownloadService_PATH", "/sdcard/test/");
        startService(ServiceIntent);
  1. 用於下載文件的代碼是否正確? 我正確使用本服務嗎?
  2. 我想下載很多文件..那么我應該為每個不同的URL啟動服務嗎?
  3. 我想通知用戶完成的百分比..但服務沒有UI。 我應該在通知欄中這樣做嗎?

謝謝。

用於下載文件的代碼是否正確?

我不喜歡使用連接來創建完全限定的文件路徑(使用適當的File構造函數)。 捕捉異常並且不對它們做任何事情是一個非常糟糕的主意。 在Android 2.3及更高版本中,您應該考慮使用DownloadManager

否則,基本的東西可能就好了。

我想下載很多文件..那么我應該為每個不同的URL啟動服務嗎?

這應該工作正常。 請注意,它們將一次下載一個,因為IntentService只有一個后台線程。

我想通知用戶完成的百分比..但服務沒有UI。 我應該在通知欄中這樣做嗎?

這將是一個解決方案。 對此的一種變體是讓服務發送有序廣播,如果它仍在屏幕上,則由您的活動接收,或者由發出NotificationBroadcastReceiver 這是一篇博文,其中有更多內容, 這是一個展示這個概念的小樣本應用程序

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM