我正在为 Android 构建一个简单的图片库应用程序。 我希望用户在想要将图像添加到短信、电子邮件、聊天应用程序时能够从中选择图像...... 我使用了 Intent 过滤器,以便当用户想要添加图像时使我的应用程序出现在应用程序选择器菜单中:
<intent-filter>
<action android:name="android.intent.action.GET_CONTENT" />
<category android:name="android.intent.category.OPENABLE" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="image/*" />
<data android:mimeType="vnd.android.cursor.dir/image" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.PICK" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="image/*" />
<data android:mimeType="vnd.android.cursor.dir/image" />
</intent-filter>
<intent-filter>
<action android:name="android.media.action.IMAGE_CAPTURE" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
然后用户可以选择图像,但我正在寻找用它响应调用者应用程序的最佳方式。
我一直在尝试将图像存储为临时文件并发送该文件的 URI
public void respondWithImage(Bitmap bitmap){
try {
//If needed create temp folder
File folder = new File(Environment.getExternalStorageDirectory() + "/temp/");
if (!folder.exists()) {
folder.mkdirs();
}
File nomediaFile = new File(folder, ".nomedia");
if (!nomediaFile.exists()) {
nomediaFile.createNewFile();
}
//Create temp image file
FileOutputStream out = new FileOutputStream(
Environment.getExternalStorageDirectory()
+ "/temp/temp.png");
bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
File bitmapFile = new File(
Environment.getExternalStorageDirectory()
+ "/temp/temp.png");
//Tell parent activity to respond with the image
if (bitmapFile.exists()) {
Intent localIntent = new Intent().setData(Uri
.fromFile(bitmapFile));
parentActivity.setResult(Activity.RESULT_OK, localIntent);
} else {
parentActivity.setResult(Activity.RESULT_CANCELED);
}
parentActivity.finish();
} catch (Exception e) {
e.printStackTrace();
Log.d("error", "Error writing data");
}
}
这可行,但我想知道如果手机没有 SD 卡会怎样。我无法尝试该选项,因为我有一个 GS3,它显然将自己的内存视为扩展卡(如果我错了,请纠正我)
我还尝试发回一个指向我的应用程序内的可绘制资源(PNG 文件)的 URI(在我的情况下,应用程序资源中包含图像不会成为问题)但它会使调用应用程序 (MMS) 崩溃,并且我没有在调试器中捕获错误。
正确的做法是什么?
最佳答案
This works but I wonder what it would do if the phone has no sdcard
您没有使用“sdcard”。
I can't try that option because i got a GS3 which apparently considers its own memory as an ext card (correct me if I'm wrong)
外部存储通常是板载闪存,通常位于内部存储所在的同一分区上。而the documentation for external storage不太好,您不妨回顾一下。
I have also tried to send back an URI which points to a drawable resource (PNG file) from within my app... but it makes the calling app (MMS) crash and I don't catch the error in debugger.
您不会在调试器中遇到来自某些第三方应用程序的崩溃,因为您正在调试您的应用程序,而不是第三方应用程序。不过,LogCat 可能包含堆栈跟踪。
What is the correct way to do that?
Use FileProvider
,或者my StreamProvider
,提供一个 ContentProvider
来提供您的图像。您的 Uri
将是 content://
Uri
。大多数应用程序都应该支持这一点,因为图像通常来自内容提供商(例如电子邮件附件)。
关于Android - 将图像传递到另一个应用程序作为对 Intent 的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22201602/