如何分享Android应用内生成的Bitmap图片?附二维码生成代码
Hey there! Based on your existing QR code generation code, let's walk through how to add sharing functionality for WhatsApp and email. Here's what you need to do:
Step 1: Prepare Permissions & File Provider (For Android 7.0+)
First, you need to handle file access properly, especially for newer Android versions.
Add this to your AndroidManifest.xml (inside the <application> tag) to set up a File Provider, which lets you safely share files with other apps:
<provider android:name="androidx.core.content.FileProvider" android:authorities="${applicationId}.fileprovider" android:exported="false" android:grantUriPermissions="true"> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths" /> </provider>
Then create a res/xml/file_paths.xml file with this content to define which files your app can share:
<?xml version="1.0" encoding="utf-8"?> <paths xmlns:android="http://schemas.android.com/apk/res/android"> <external-files-path name="my_images" path="Pictures" /> </paths>
Note: Using getExternalFilesDir() means you don't need to request WRITE_EXTERNAL_STORAGE permission (since Android 10+), as this directory is private to your app but accessible to other apps via File Provider.
Step 2: Save the Generated Bitmap to a File
Add this method to your activity to save the QR code Bitmap to a local file:
private Uri saveBitmapToFile(Bitmap bitmap) { // Get the app's private Pictures directory File picturesDir = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "QR Codes"); if (!picturesDir.exists()) { picturesDir.mkdirs(); } // Create a unique filename (you can adjust this as needed) String fileName = "QR_" + System.currentTimeMillis() + ".png"; File imageFile = new File(picturesDir, fileName); try (FileOutputStream fos = new FileOutputStream(imageFile)) { bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos); fos.flush(); // Get the content URI using File Provider return FileProvider.getUriForFile(this, getPackageName() + ".fileprovider", imageFile); } catch (IOException e) { e.printStackTrace(); return null; } }
Step 3: Create the Sharing Intent
Add this method to handle sharing the image via WhatsApp, email, or other apps:
private void shareImage(Uri imageUri) { if (imageUri == null) { Toast.makeText(this, "Failed to save image for sharing", Toast.LENGTH_SHORT).show(); return; } // Create base share intent Intent shareIntent = new Intent(Intent.ACTION_SEND); shareIntent.setType("image/png"); shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri); shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); // Grant access to the file // Option 1: Let the user choose which app to share with startActivity(Intent.createChooser(shareIntent, "Share QR Code via")); // Option 2: Directly share to WhatsApp (if installed) /* PackageManager pm = getPackageManager(); try { Intent whatsAppIntent = new Intent(Intent.ACTION_SEND); whatsAppIntent.setPackage("com.whatsapp"); whatsAppIntent.setType("image/png"); whatsAppIntent.putExtra(Intent.EXTRA_STREAM, imageUri); whatsAppIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); startActivity(whatsAppIntent); } catch (ActivityNotFoundException e) { Toast.makeText(this, "WhatsApp not installed", Toast.LENGTH_SHORT).show(); } */ // Option 3: Directly share via email /* Intent emailIntent = new Intent(Intent.ACTION_SEND); emailIntent.setType("image/png"); emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{"recipient@example.com"}); emailIntent.putExtra(Intent.EXTRA_SUBJECT, "My QR Code"); emailIntent.putExtra(Intent.EXTRA_TEXT, "Here's the QR code I generated!"); emailIntent.putExtra(Intent.EXTRA_STREAM, imageUri); emailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); startActivity(Intent.createChooser(emailIntent, "Send QR Code via Email")); */ }
Step 4: Integrate with Your Existing QR Code Generation
Update your gerarQRCode() method to save the bitmap and trigger sharing (or link this to a button click event if you don't want to share immediately):
private void gerarQRCode() { String texto = edtTexto.getText().toString(); MultiFormatWriter multiFormatWriter = new MultiFormatWriter(); try { BitMatrix bitmatrix = multiFormatWriter.encode(texto, BarcodeFormat.QR_CODE, 2000, 2000); BarcodeEncoder barcodeEncoder = new BarcodeEncoder(); Bitmap bitmap = barcodeEncoder.createBitmap(bitmatrix); ivQRCode.setImageBitmap(bitmap); // Save and share the QR code (call this here, or link to a button click) Uri imageUri = saveBitmapToFile(bitmap); shareImage(imageUri); } catch (WriterException e) { e.printStackTrace(); } }
Key Notes:
- Permissions: For Android 9 and below, you may need to request
WRITE_EXTERNAL_STORAGEpermission at runtime. For Android 10+, usinggetExternalFilesDir()avoids this requirement. - Error Handling: Make sure to handle cases where the bitmap fails to save, or the target app (like WhatsApp) isn't installed.
- File Cleanup: You might want to add logic to delete old QR code files periodically to save storage space.
内容的提问来源于stack exchange,提问作者Almir Kubo

