Android 图片下载功能实现:从 API 获取链接并下载
Android 图片下载功能实现:从 API 获取链接并下载
本文将详细介绍如何在 Android 应用中实现图片下载功能,包括从 API 获取图片链接、使用 OkHttpClient 下载图片以及使用 DownloadManager 进行下载管理,并提供示例代码和优化建议。
1. 从 API 获取图片链接
首先,你需要使用 Android 中的网络库(例如 OkHttpClient)向 API 发送请求,获取图片链接。以下示例代码演示了如何使用 OkHttpClient 从 API 获取图片链接:
public void dow_imgone(final View view) {
new AsyncTask<Void, Void, String>() {
protected String doInBackground(Void... voids) {
OkHttpClient client = new OkHttpClient();
EditText editText = findViewById(R.id.edit_text);
String inputText = editText.getText().toString();
if (inputText.isEmpty()) {
Snackbar.make(view, 'mit:你人还怪好的嘞', Snackbar.LENGTH_LONG)
.setAction('Action', null).show();
return '输入框为空';
}
String url = 'https://app.huashijie.art/api/work/detailV2?visitorId=-1&workId=' + inputText + '&cur_user_id=-1&platform=android&os_version=28&version_code=217&device_brand=vivo&device_model=vivo%20X21&token=&channel=vivo';
Request request = new Request.Builder()
.url(url)
.build();
try {
Response response = client.newCall(request).execute();
String responseBody = response.body().string();
JsonParser parser = new JsonParser();
JsonObject json = parser.parse(responseBody).getAsJsonObject();
String imageUrl = json.get('data').getAsJsonObject().get('multiImages').getAsJsonArray().get(0).getAsJsonObject().get('imgPath').getAsString();
if (imageUrl != null && imageUrl.matches('http://bsyimg\.pandapaint\.net/v2/work_cover/user/[0-9]+/[0-9]+\.jpg')) {
String fileName = 'image.jpg';
File downloadDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File outputFile = new File(downloadDir, fileName);
downloadImage(imageUrl, outputFile);
return '获取链接成功' + imageUrl;
} else {
return '未能提取到图片地址';
}
} catch (IOException e) {
e.printStackTrace();
return '下载失败';
}
}
protected void onPostExecute(String result) {
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show();
}
}.execute();
}
private void downloadImage(String imageUrl, File outputFile) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(imageUrl)
.build();
try {
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
FileOutputStream fos = new FileOutputStream(outputFile);
fos.write(response.body().bytes());
fos.close();
Toast.makeText(this, '下载已完成', Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void downloadImage(String imageUrl) {
DownloadManager downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
Uri downloadUri = Uri.parse(imageUrl);
DownloadManager.Request request = new DownloadManager.Request(downloadUri);
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(false)
.setTitle('Image')
.setDescription('Downloading image...')
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
.setDestinationInExternalPublicDir(Environment.DIRECTORY_PICTURES, 'image.jpg');
downloadManager.enqueue(request);
Toast.makeText(this, '下载已启动', Toast.LENGTH_SHORT).show();
}
2. 使用 OkHttpClient 下载图片
获取到图片链接后,可以使用 OkHttpClient 下载图片到本地存储。以下示例代码演示了如何使用 OkHttpClient 下载图片:
private void downloadImage(String imageUrl, File outputFile) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(imageUrl)
.build();
try {
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
FileOutputStream fos = new FileOutputStream(outputFile);
fos.write(response.body().bytes());
fos.close();
Toast.makeText(this, '下载已完成', Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
e.printStackTrace();
}
}
3. 使用 DownloadManager 进行下载管理
除了使用 OkHttpClient 下载图片,Android 还提供了 DownloadManager 类来进行下载管理,它可以更方便地处理下载任务,并提供通知等功能。以下示例代码演示了如何使用 DownloadManager 下载图片:
private void downloadImage(String imageUrl) {
DownloadManager downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
Uri downloadUri = Uri.parse(imageUrl);
DownloadManager.Request request = new DownloadManager.Request(downloadUri);
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(false)
.setTitle('Image')
.setDescription('Downloading image...')
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
.setDestinationInExternalPublicDir(Environment.DIRECTORY_PICTURES, 'image.jpg');
downloadManager.enqueue(request);
Toast.makeText(this, '下载已启动', Toast.LENGTH_SHORT).show();
}
4. 优化建议
- 使用线程池管理下载任务,避免过多线程占用系统资源。
- 使用缓存机制,避免重复下载相同图片。
- 使用进度条显示下载进度,提升用户体验。
- 使用错误处理机制,处理网络异常、文件写入失败等问题。
总结
本文详细介绍了如何在 Android 应用中实现图片下载功能,并提供了示例代码和优化建议。开发者可以根据实际需求选择合适的下载方式,并进行优化,提升应用的性能和用户体验。
原文地址: https://www.cveoy.top/t/topic/hhp8 著作权归作者所有。请勿转载和采集!