我正在尝试以编程方式截取屏幕截图,然后使用 Intent 将其共享到另一个应用程序。我面临的问题是照片是作为文本文件发送的。
按钮监听器如下所示:
shareButton = rootView.findViewById(R.id.shareButton);
shareButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Bitmap screenshot = Screenshot.takeScreenshot(view.getRootView());
String filename = "eduMediaPlayerScreenshot";
String sharePath = Screenshot.storeScreenshot(screenshot, filename);
Intent intent = Screenshot.shareScreenshot(sharePath, view.getRootView());
startActivity(intent);
}
});
屏幕截图类是这样的:
public class Screenshot {
public static Bitmap takeScreenshot(View view) {
view.setDrawingCacheEnabled(true);
view.buildDrawingCache(true);
Bitmap screenshot = Bitmap.createBitmap(view.getDrawingCache());
view.setDrawingCacheEnabled(false);
return screenshot;
}
public static String storeScreenshot(Bitmap screenshot, String filename) {
String path = Environment.getExternalStorageDirectory().toString() + "/" + filename;
OutputStream out = null;
File imageFile = new File(path);
try {
out = new FileOutputStream(imageFile);
screenshot.compress(Bitmap.CompressFormat.JPEG, 99, out);
out.flush();
} catch (FileNotFoundException e) {
Log.i("Exception:", "File not found.");
} catch (IOException e) {
Log.i("Exception:", "Cannot write to output file.");
} finally {
try {
if (out != null) {
out.close();
return imageFile.toString();
}
} catch (Exception e) {
Log.i("Exception:", "No output file to close.");
}
}
return null;
}
public static Intent shareScreenshot(String sharePath, View view) {
File file = new File(sharePath);
Uri uri = FileProvider.getUriForFile(view.getContext(),
BuildConfig.APPLICATION_ID + ".provider", file);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_STREAM, uri);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
return intent;
}
}
分享的照片是这样的: not-the-best-photo
最佳答案
由于默认情况下 Android 无法识别没有扩展名的图像,因此您应该按照上述 Intent 将 .jpg
添加到文件名的末尾。没有它,应该指定一个 MIME 类型。更多详情here .
这是您可能想要使用的代码。
shareButton = rootView.findViewById(R.id.shareButton);
shareButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Bitmap screenshot = Screenshot.takeScreenshot(view.getRootView());
String filename = "eduMediaPlayerScreenshot.jpg";
String sharePath = Screenshot.storeScreenshot(screenshot, filename);
Intent intent = Screenshot.shareScreenshot(sharePath, view.getRootView());
startActivity(intent);
}
});
关于android - 使用 Intent 在 Android 应用程序中共享图像将其作为文本文件而不是照片发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53981031/