Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/http/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 在API级别9+上使用DownloadManager下载文件,并返回到AsyncTask9时使用DownloadManager,当API级别>9时使用AsyncTask解决方案_Android_Http_Download_Android 2.3 Gingerbread_Android Download Manager - Fatal编程技术网

Android 在API级别9+上使用DownloadManager下载文件,并返回到AsyncTask9时使用DownloadManager,当API级别>9时使用AsyncTask解决方案

Android 在API级别9+上使用DownloadManager下载文件,并返回到AsyncTask9时使用DownloadManager,当API级别>9时使用AsyncTask解决方案,android,http,download,android-2.3-gingerbread,android-download-manager,Android,Http,Download,Android 2.3 Gingerbread,Android Download Manager,我有一个服务类,可以处理特定文件的下载 第一个版本是使用AsyncTask编写的。因为它是一个大文件,通过HTTPS,所以使用DownloadManager会很好,所以我重构了服务以使用DownloadManager服务 我如何自己构建一个服务类,当支持的API级别>9时使用DownloadManager,当API级别>9时使用AsyncTask解决方案 我如何自己构建一个服务类,在需要时使用DownloadManager 支持的API级别>9,并在 回答我自己的问题,以下是我所做的: 构建抽象

我有一个服务类,可以处理特定文件的下载

第一个版本是使用AsyncTask编写的。因为它是一个大文件,通过HTTPS,所以使用DownloadManager会很好,所以我重构了服务以使用DownloadManager服务

我如何自己构建一个服务类,当支持的API级别>9时使用DownloadManager,当API级别>9时使用AsyncTask解决方案 我如何自己构建一个服务类,在需要时使用DownloadManager 支持的API级别>9,并在
回答我自己的问题,以下是我所做的:

构建抽象服务基类,例如DownloadService 扩展到具体的子类,例如AsyncTaskDownloadService和DownloadManagerDownloadService 创建服务时,请使用功能检测而不是构建级别。对我来说,这更优雅,如下所示:

Activity activity = getActivity();
Object downloadService = activity.getSystemService(Context.DOWNLOAD_SERVICE);
Class serviceClass = AsyncTaskDownloadService.class;
if (downloadService != null) {
    serviceClass = DownloadManagerDownloadService.class;
}
Intent serviceIntent = new Intent(activity, serviceClass);
activity.startService(serviceIntent);

<>这将在API级别=9时使用较老的方法。

我会认真考虑它是否值得,编码谷歌Play服务甚至支持API级别9 +。我还建议您不要这样做。谢谢,但我们必须支持。谢谢,我更喜欢在可能的情况下使用功能检测,而不是依赖构建版本。这在这里可能没有必要,但当试图证明未来时,这是一个很好的实践。另外,由于不同的方法涉及大量不同的代码,我更喜欢使用两个不同的类,并在运行时实例化正确的类,而不是每个构建版本都有大量不同代码路径的类。
Activity activity = getActivity();
Object downloadService = activity.getSystemService(Context.DOWNLOAD_SERVICE);
Class serviceClass = AsyncTaskDownloadService.class;
if (downloadService != null) {
    serviceClass = DownloadManagerDownloadService.class;
}
Intent serviceIntent = new Intent(activity, serviceClass);
activity.startService(serviceIntent);