"file:///storage/emulated/0/screenshot.png exposed beyond app through ClipData.Item.getUri()"



我正在尝试在我的应用程序上设置共享按钮。该按钮应该截取特定列表视图的屏幕截图,然后允许用户通过他们想要的任何方式共享此图像。为此,我创建了三种方法:

  1. 截取屏幕截图
  2. 将其保存在我的存储中
  3. 将其共享给用户。

为此,我编写了以下代码:

public class ViewPlayerHistoryContents extends AppCompatActivity {    
public static File imagePath;
public Bitmap takeScreenshot() {
View rootView = findViewById(android.R.id.content).getRootView();
rootView.setDrawingCacheEnabled(true);
return rootView.getDrawingCache();
}
public void saveBitmap(Bitmap bitmap) {
imagePath = new File(Environment.getExternalStorageDirectory() + "/screenshot.png");
FileOutputStream fos;
try {
fos = new FileOutputStream(imagePath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
Log.e("GREC", e.getMessage(), e);
} catch (IOException e) {
Log.e("GREC", e.getMessage(), e);
}
}
private void shareIt() {
Uri uri = Uri.fromFile(imagePath);
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("image/*");
String shareBody = "In Tweecher, My highest score with screen shot";
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "My Tweecher score");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
sharingIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(sharingIntent, "Share via"));
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_player_history);        
shareButton = findViewById(R.id.shareButton);    
View rootView = getWindow().getDecorView().findViewById(android.R.id.content);
shareButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Bitmap bitmap = takeScreenshot();
saveBitmap(bitmap);
shareIt();    
}
});        
}
}

使用此代码,我不断收到以下错误消息:

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.transfergame, PID: 18477
android.os.FileUriExposedException: file:///storage/emulated/0/screenshot.png exposed beyond app through ClipData.Item.getUri()

对我来说,这听起来像是因为我使用的是 Uri 而不是 FileProvider?

我应该如何将 FileProvider 纳入其中?

我向我的 Android 清单文件添加了以下权限,但它没有执行任何操作:

</application>        
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

如何修复此错误?

谢谢大家

你可以通过这个

您已在 android 清单中添加提供程序,并在 xml/提供程序中创建文件提供程序.xml如链接中的答案所示。

public void captureImage() {
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
activity.startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}

最新更新