gpt4 book ai didi

java - 尝试共享图像时出错

转载 作者:行者123 更新时间:2023-12-01 11:33:48 25 4
gpt4 key购买 nike

所以我截取了我的 Activity 的屏幕截图,然后将其保存到“screenshot.png”。当尝试通过 Whatsapp 共享它时,我收到错误:“无法发送图像”。与 gmail、pushbullet 和基本上所有其他应用程序相同。因此,我得出结论,文件以某种方式存在,但它要么是空的,要么是困惑的......老实说,我不知道。

代码如下:

截取 Activity 屏幕截图:

public Bitmap takeScreenshot() {
View rootView = findViewById(android.R.id.content).getRootView();
rootView.setDrawingCacheEnabled(true);
return rootView.getDrawingCache();
}

保存屏幕截图:

public void saveBitmap(Bitmap bitmap) {
FileOutputStream fos;
String filePath = getApplicationContext().getFilesDir().getPath().toString() + "/screenshot.png";
File f = new File(filePath);
try {
fos = new FileOutputStream(f);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
Log.e("GREC", e.getMessage(), e);
} catch (IOException e) {
Log.e("GREC", e.getMessage(), e);
}
}

最后,分享本身:

if (id == R.id.action_share){
Bitmap bitmap = takeScreenshot();
saveBitmap(bitmap);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/png");
share.putExtra(Intent.EXTRA_STREAM, Uri.parse("screenshot.png"));
startActivity(Intent.createChooser(share, "Teilen via"));
}

我的错误在哪里?我在 logcat 中没有收到任何错误,但无法共享“屏幕截图”。

最佳答案

首先,您应该使用:

share.putExtra(Intent.EXTRA_STREAM.Uri.fromFile(new File(getApplicationContext().getFilesDir().getPath().toString() + "/screenshot.png"));

但是您会收到“附件的权限被拒绝”,您可能会尝试但没有运气:(

share.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

因此,处理此问题的最佳方法可能是将捕获的屏幕截图存储在媒体库中并从那里发送文件。

public void share() {
String filePath=getApplicationContext().getFilesDir().getPath().toString() + "/screenshot.png";
String path;
try {
path = Images.Media.insertImage(getContentResolver(), filePath, "title", null);
Uri screenshotUri = Uri.parse(path);

Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/png");
share.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
share.putExtra(Intent.EXTRA_STREAM, screenshotUri);
startActivity(Intent.createChooser(share, "Teilen via"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}

希望对你有帮助!

关于java - 尝试共享图像时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30200254/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com