android在ImageView中共享图像而不保存在sd卡中
我想在图像视图中共享图像,但不想保存到SD卡。 但当我使用意图分享时,我使用了代码android在ImageView中共享图像而不保存在sd卡中,android,bitmap,Android,Bitmap,我想在图像视图中共享图像,但不想保存到SD卡。 但当我使用意图分享时,我使用了代码 Intent share = new Intent(Intent.ACTION_SEND); share.setType("image/jpeg"); share.putExtra(Intent.EXTRA_STREAM,Uri.parse(path)); startActivity(Intent.createChoo
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
share.putExtra(Intent.EXTRA_STREAM,Uri.parse(path));
startActivity(Intent.createChooser(share, "Share Image"));
此处路径指定SD卡中图像的位置
但我不想保存图像。。。有可能吗 您还可以将其作为媒体库内容提供商URI共享(如果图像已经在手机上,或者如果它来自web,您可以共享URL(尽管效果不同) 但是如果你从网上直接解码成位图,现在想把它作为一个合适的图像共享,是的,你真的需要这个文件!我可以做到:
File file = new File( getCacheDir(), "screenshot.png");
...
file.setReadable(true, false);
Uri uri = Uri.fromFile(file);
...
intent.putExtra(Intent.EXTRA_STREAM, uri);
通过这种方式,我将文件保存在自己的缓存文件夹中,因此我不会愚弄任何公用文件夹或依赖sd卡
同样,如果用户删除我的应用程序,它会自动被删除,但我也使用startActivityForResult/onActivityResult删除文件,并在共享完成后将其文件夹设置回private
(就我个人而言,我希望找到一种共享比特流的方法,并完全避免创建文件的步骤,但我认为这是不可能的。)
[编辑:我发现这在2.3.6上不起作用,因为文件必须在2.3.6上file:///mnt/sdcard.]与其他应用程序共享文件的推荐方法是调用。文档非常好,但有些部分有点棘手。下面是一个总结 在清单中设置文件提供程序 这将告诉文件提供程序从何处获取要共享的文件(在本例中使用缓存目录) 将映像保存到内部存储器 分享图像 进一步阅读
AndroidX.core.content.FileProvider
出于某种原因,只使用setDataAndType
或putExtra(Intent.EXTRA_STREAM,…)
对我不起作用。两种方法都可以解决问题
<manifest>
...
<application>
...
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.example.myapp.fileprovider"
android:grantUriPermissions="true"
android:exported="false">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/filepaths" />
</provider>
...
</application>
</manifest>
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<cache-path name="shared_images" path="images/"/>
</paths>
// save bitmap to cache directory
try {
File cachePath = new File(context.getCacheDir(), "images");
cachePath.mkdirs(); // don't forget to make the directory
FileOutputStream stream = new FileOutputStream(new File(cachePath, "image.png")); // overwrites this image every time
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
stream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
File imagePath = new File(context.getCacheDir(), "images");
File newFile = new File(imagePath, "image.png");
Uri contentUri = FileProvider.getUriForFile(context, "com.example.app.fileprovider", newFile);
if (contentUri != null) {
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); // temp permission for receiving app to read this file
shareIntent.setDataAndType(contentUri, getContentResolver().getType(contentUri));
shareIntent.putExtra(Intent.EXTRA_STREAM, contentUri);
startActivity(Intent.createChooser(shareIntent, "Choose an app"));
}