在Android开发中,可以通过以下步骤下载图片并通过Bitmap设置ImageView: 1. 创建一个ImageView对象。 ```java ImageView imageView = findViewById(R.id.imageView); ``` 2. 创建一个BitmapFactory对象。 ```java BitmapFactory bitmapFactory = BitmapFactory.Options(); ``` 3. 创建一个DownloadManager对象。 ```java DownloadManager downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE); ``` 4. 创建一个DownloadRequest对象。 ```java DownloadRequest request = new DownloadRequest.Builder() .setUri("http://example.com/image.jpg") .setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "image.jpg") .build(); ``` 5. 下载图片。 ```java DownloadManager.Request request = new DownloadManager.Request(Uri.parse("http://example.com/image.jpg")); request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "image.jpg"); DownloadManager downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE); downloadManager.enqueue(request); ``` 6. 下载完成后,获取下载的Bitmap并设置到ImageView。 ```java DownloadManager.Request request = new DownloadManager.Request(Uri.parse("http://example.com/image.jpg")); request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "image.jpg"); DownloadManager downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE); DownloadManager.Query query = new DownloadManager.Query(); query.setFilterById(downloadManager.getNextSyncId()); Cursor cursor = downloadManager.query(query); while (cursor.moveToNext()) { long id = cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_ID)); DownloadManager.Request request = new DownloadManager.Request(Uri.parse("http://example.com/image.jpg")); request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "image.jpg"); DownloadManager.Status status = downloadManager.getStatus(id); if (status.isDone()) { try { File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "image.jpg"); BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(file.getAbsolutePath(), options); options.inSampleSize = calculateInSampleSize(options, 100, 100); options.inJustDecodeBounds = false; Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), options); imageView.setImageBitmap(bitmap); } catch (Exception e) { e.printStackTrace(); } } } cursor.close(); ``` 注意:在实际开发中,可能需要处理网络请求失败、下载失败等情况。 [2023-11-08 00:25:11 | AI问答 | 524点数解答]