0

我正在开发一个应用程序,我需要在其中下载一个大小为 5 到 50 MB 的文件(.zip / .txt / .jpg 等)。基于 Android 2.2 的应用程序。

用户提供URL并触发下载,然后下载过程在后台运行,直到完成。

应该用于下载文件。
我想知道如何使用HTTP 连接来完成。可以为此使用
哪些类?
android 2.2 是否为此提供了 API?

任何形式的帮助表示赞赏....

4

1 回答 1

9

Android 确实包含了一个DownloadManager为此目的而调用的 API……但它是在 2.3 中发布的;因此,虽然它在您的应用程序以 2.2 为目标时不会有用,但它可能仍然是您研究实现的好资源。

我推荐的一个简单实现是这样的:

  • 使用HttpURLConnection连接和下载数据。这将需要在您的清单中声明 INTERNET 权限
  • 确定您希望文件的位置。如果您希望它在设备的 SD 卡上,您还需要 WRITE_EXTERNAL_STORAGE 权限。
  • 将此操作包装在 .doInBackground() 方法中AsyncTask。这是一个长时间运行的操作,因此您需要将其放入 AsyncTask 为您管理的后台线程中。
  • 在 a 中实现这一点,Service这样操作就可以在受保护的情况下运行,而无需用户将 Activity 保持在前台。
  • 用于NotificationManager在下载完成时通知用户,这将在他们的状态栏上发布一条消息。

为了进一步简化事情,如果您使用IntentService,它将为您处理线程(所有内容都在onHandleIntent后台线程上调用),您可以通过简单地向它发送多个 Intent 来排队多个下载以一次处理一个。这是我所说的一个骨架示例:

public class DownloadService extends IntentService {

public static final String EXTRA_URL = "extra_url";
public static final int NOTE_ID = 100;

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

@Override
protected void onHandleIntent(Intent intent) {
    if(!intent.hasExtra(EXTRA_URL)) {
        //This Intent doesn't have anything for us
        return;
    }
    String url = intent.getStringExtra(EXTRA_URL);
    boolean result = false;
    try {
        URL url = new URL(params[0]);
        HttpURLConnection connection = (HttpURLConnection)url.openConnection();
        //Input stream from the connection
        InputStream in = new BufferedInputStream(connection.getInputStream());
        //Output stream to a file in your application's private space
        FileOutputStream out = openFileOutput("filename", Activity.MODE_PRIVATE);

        //Read and write the stream data here

        result = true;
    } catch (Exception e) {
        e.printStackTrace();
    }

    //Post a notification once complete
    NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    Notification note;
    if(result) {
        note = new Notification(0, "Download Complete", System.currentTimeMillis());
    } else {
        note = new Notification(0, "Download Failed", System.currentTimeMillis());
    }
    manager.notify(NOTE_ID, note);

}
}

然后,您可以使用要在 Activity 中的任何位置下载的 URL 调用此服务,如下所示:

Intent intent = new Intent(this, DownloadService.class);
intent.putExtra(DownloadService.EXTRA_URL,"http://your.url.here");
startService(intent);

希望这有帮助!

编辑:我正在修复这个示例,以便为以后遇到此问题的任何人删除不必要的双线程。

于 2011-02-01T20:43:48.173 回答