一、使用系统下载管理器下载文件
Android系统提供了一个简单易用的下载管理器,可以方便地下载文件。使用系统下载管理器下载文件的步骤如下:
1、在AndroidManifest.xml文件中加入以下下载权限。
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
2、创建一个DownloadManager.Request对象,并设置下载文件的相关参数,如下载地址、标题、描述、存储路径等。
DownloadManager.Request request = new DownloadManager.Request(Uri.parse("http://example.com/file.mp3")); request.setTitle("文件名"); request.setDescription("下载中..."); request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE); request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "file.mp3");
3、获取系统下载管理器,并调用enqueue方法添加下载任务。
DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); long downloadId = downloadManager.enqueue(request);
4、接收下载完成的广播。
class DownloadReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1); DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); DownloadManager.Query query = new DownloadManager.Query(); query.setFilterById(downloadId); Cursor cursor = downloadManager.query(query); if (cursor.moveToFirst()) { int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)); if (status == DownloadManager.STATUS_SUCCESSFUL) { String fileName = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_TITLE)); String filePath = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI)); Toast.makeText(context, fileName + "下载成功,保存路径为:" + filePath, Toast.LENGTH_SHORT).show(); } else { String reason = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_REASON)); Toast.makeText(context, "下载失败,原因:" + reason, Toast.LENGTH_SHORT).show(); } } cursor.close(); } }
二、使用OkHttp下载文件
在Android中,通常使用第三方库OkHttp来实现HTTP请求,包括文件下载。使用OkHttp下载文件的步骤如下:
1、添加OkHttp库的依赖。
dependencies { implementation 'com.squareup.okhttp3:okhttp:4.9.0' }
2、创建OkHttpClient对象,并使用它来创建一个Request对象。
OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url("http://example.com/file.mp3") .build();
3、使用OkHttpClient对象执行Request请求,获取Response对象。
Response response = client.newCall(request).execute();
4、通过Response对象获取ResponseBody,将文件内容写入本地文件中。
String fileName = "file.mp3"; File outFile = new File(getExternalFilesDir(null), fileName); InputStream inputStream = null; OutputStream outputStream = null; try { if (response.isSuccessful()) { inputStream = response.body().byteStream(); outputStream = new FileOutputStream(outFile); byte[] buffer = new byte[4096]; int len = 0; while ((len = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, len); } outputStream.flush(); Toast.makeText(this, fileName + "下载成功,保存路径为:" + outFile.getAbsolutePath(), Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, "下载失败,错误码:" + response.code(), Toast.LENGTH_SHORT).show(); } } catch (IOException e) { e.printStackTrace(); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (outputStream != null) { try { outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } }
三、使用DownloadTask下载文件
如果你不想使用系统下载管理器或者OkHttp库,也可以通过自定义DownloadTask类来完成文件下载。DownloadTask通过HttpURLConnection发送请求,获取文件内容后保存到本地文件中。DownloadTask实现文件下载的步骤如下:
1、创建一个DownloadTask类,继承AsyncTask。
public class DownloadTask extends AsyncTask<String, Integer, String> { @Override protected String doInBackground(String... params) { String url = params[0]; String fileName = params[1]; InputStream inputStream = null; OutputStream outputStream = null; HttpURLConnection connection = null; try { URL downloadUrl = new URL(url); connection = (HttpURLConnection) downloadUrl.openConnection(); connection.connect(); inputStream = connection.getInputStream(); outputStream = new FileOutputStream(new File(getExternalFilesDir(null), fileName)); byte[] buffer = new byte[4096]; int len = 0; int totalLength = connection.getContentLength(); int downloadedLength = 0; while ((len = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, len); downloadedLength += len; if (totalLength > 0) { publishProgress((int) (downloadedLength * 100 / totalLength)); } } outputStream.flush(); return fileName; } catch (IOException e) { e.printStackTrace(); return null; } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (outputStream != null) { try { outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (connection != null) { connection.disconnect(); } } } @Override protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); int progress = values[0]; Log.d("DownloadTask", "下载进度:" + progress); } @Override protected void onPostExecute(String result) { super.onPostExecute(result); if (result == null) { Toast.makeText(MainActivity.this, "下载失败", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MainActivity.this, result + "下载成功,保存路径为:" + getExternalFilesDir(null) + "/" + result, Toast.LENGTH_SHORT).show(); } } }
2、通过DownloadTask的execute方法调用。
new DownloadTask().execute("http://example.com/file.mp3", "file.mp3");
3、在onProgressUpdate方法中更新下载进度。
以上就是三种不同的下载文件的方式,可以根据不同的场景选择不同的方法。