我知道我们可以在 Android 2.3 及更高版本中使用内置下载管理器,但我的应用适用于 Android 2.2 及更高版本。我的问题是如何在 android 2.2 中创建自己的下载管理器?请给我一些示例答案。
1 回答
请给我一些示例答案。
Step1 寻找有关如何在 Android 中下载文件的示例
Step2 查找有关如何在 AsyncTask 中执行操作的示例。
步骤 3 查找有关如何在下载时显示下载进度的示例。
Step4 查找任务完成时如何发送自定义广播的示例
Step5 寻找如何在设备旋转时保持 AsysncTask 操作的示例
Step6 查找有关如何在通知中显示下载进度的示例。
下面是示例代码。
1. 使用 AsyncTask 并在对话框中显示下载进度
// declare the dialog as a member field of your activity
ProgressDialog mProgressDialog;
// instantiate it within the onCreate method
mProgressDialog = new ProgressDialog(YourActivity.this);
mProgressDialog.setMessage("A message");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
// execute this when the downloader must be fired
DownloadFile downloadFile = new DownloadFile();
downloadFile.execute("the url to the file you want to download");
The AsyncTask will look like this:
// usually, subclasses of AsyncTask are declared inside the activity class.
// that way, you can easily modify the UI thread from here
private class DownloadFile extends AsyncTask<String, Integer, String> {
@Override
protected String doInBackground(String... sUrl) {
try {
URL url = new URL(sUrl[0]);
URLConnection connection = url.openConnection();
connection.connect();
// this will be useful so that you can show a typical 0-100% progress bar
int fileLength = connection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/file_name.extension");
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
}
return null;
}
上面的方法(doInBackground)总是在后台线程上运行。你不应该在那里做任何 UI 任务。另一方面,onProgressUpdate 和 onPreExecute 在 UI 线程上运行,因此您可以更改进度条:
@Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog.show();
}
@Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
mProgressDialog.setProgress(progress[0]);
}
}
2.从服务下载
这里最大的问题是:如何从服务更新我的活动?在下一个示例中,我们将使用您可能不知道的两个类:ResultReceiver 和 IntentService。ResultReceiver 允许我们从服务更新我们的线程;IntentService 是 Service 的一个子类,它产生一个线程来从那里做后台工作(你应该知道一个 Service 实际上在你的应用程序的同一个线程中运行;当你扩展 Service 时,你必须手动产生新线程来运行 CPU 阻塞操作) .
下载服务可能如下所示:
public class DownloadService extends IntentService {
public static final int UPDATE_PROGRESS = 8344;
public DownloadService() {
super("DownloadService");
}
@Override
protected void onHandleIntent(Intent intent) {
String urlToDownload = intent.getStringExtra("url");
ResultReceiver receiver = (ResultReceiver) intent.getParcelableExtra("receiver");
try {
URL url = new URL(urlToDownload);
URLConnection connection = url.openConnection();
connection.connect();
// this will be useful so that you can show a typical 0-100% progress bar
int fileLength = connection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/BarcodeScanner-debug.apk");
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
Bundle resultData = new Bundle();
resultData.putInt("progress" ,(int) (total * 100 / fileLength));
receiver.send(UPDATE_PROGRESS, resultData);
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
}
Bundle resultData = new Bundle();
resultData.putInt("progress" ,100);
receiver.send(UPDATE_PROGRESS, resultData);
}
}
将服务添加到您的清单中:
<service android:name=".DownloadService"/>
活动将如下所示:
// 像第一个例子一样初始化进度对话框
// 这就是你触发下载器的方式
mProgressDialog.show();
Intent intent = new Intent(this, DownloadService.class);
intent.putExtra("url", "url of the file to download");
intent.putExtra("receiver", new DownloadReceiver(new Handler()));
startService(intent);
这是 ResultReceiver 来玩的:
private class DownloadReceiver extends ResultReceiver{
public DownloadReceiver(Handler handler) {
super(handler);
}
@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
super.onReceiveResult(resultCode, resultData);
if (resultCode == DownloadService.UPDATE_PROGRESS) {
int progress = resultData.getInt("progress");
mProgressDialog.setProgress(progress);
if (progress == 100) {
mProgressDialog.dismiss();
}
}
}
}