我正在将图像文件共享到 WhatsApp。 Whatsapp 无法读取私有(private)文件,因此我将其保存到公共(public)目录中。
我想要 --> 当用户共享图像时,应该将其从存储中删除。
try {
String uniqueName = System.currentTimeMillis() + "";
File tempFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "ABBM-temp");
if (!tempFile.exists()) {
tempFile.mkdirs();
}
tempFile = new File(tempFile + uniqueName + ".png");
FileOutputStream fOut = new FileOutputStream(tempFile);
b.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
final Intent intent = new Intent(android.content.Intent.ACTION_SEND);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(tempFile));
intent.setType("image/png");
startActivity(Intent.createChooser(intent, "Share image via"));
//tempFile.delete();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Image not shared, please grant storage permission", Toast.LENGTH_SHORT).show();
}
上面的代码打开了共享 Intent ,但在后台删除了文件,因此我无法共享该文件。
共享文件并删除它。
谢谢你..
最佳答案
您的代码有点笨拙,并且在最新版本的 Android 中肯定会出现错误。以下是一些观察结果:
解决方案1
1。使用File Provider
并写入私有(private)存储区域
我知道您正在写入主存储,因此其他应用程序可以读取该文件,但不应该这样做。使用文件提供程序并从中获取 Uri。这是文档:File Provider Documentation 。当您设置好文件提供程序后(相信我,这很简单,您只需向 list 添加一个 fragment 并添加一个 xml 路径),您就可以私下写入内存。像这样:
FileOutputStream fOut = openFileOutput("the_name_of_file_here", Context.MODE_PRIVATE);
b.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
然后使用 getUriForFile
您可以获得一个可供您授予访问权限的任何应用程序使用的 Uri。像这样:
File file = new File(getFilesDir(), "the_name_of_file_here");
Uri uri = getUriForFile(this, "com.yourpackagename.fileprovider", file);
2。使用ShareCompat
当您设置了 FileProvider
后,我建议您在共享文件时使用 ShareCompat
而不是常规共享 Activity 。 ShareCompat 的优点是得到了 Google 的官方支持,你还可以用它共享大量文件。无需向其他应用授予URI_PERMISSION
。这是一个例子:
Intent shareIntent = ShareCompat.IntentBuilder.from(this)
.setType(type) //This is the MIME type
.setStream(uri) //This is the uri we got earlier
.getIntent();
shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(shareIntent); //Starting the activity
我建议您看看这个博客:Getting Started with Share-Compat了解更多信息。希望这会有所帮助。
解决方案2
传统解决方案:
如果您出于偏好或因为它更适合您的应用而仍想使用您的函数,您可以执行以下操作:
不要使用 startActivity(Intent)
,而是使用 startActivityForResult(Intent, int)
。这样你就可以传递一个整数值作为 id 。然后,当文件共享并且您返回到应用程序时,将触发 onActivityResult()
函数。它将有一个 requestCode
。像这样:
//Create your share intent as you do in your code, then:
startActivityForResult(intent, 512); //I passed 512 you can pass anything you want
然后重写这个函数:
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//Check if it is from the same code, if yes delete the temp file
if(requestCode == 512) {
tempFile.delete();
}
}
关于java - 在 android 中共享文件后立即删除该文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57507019/