我正在尝试以编程方式拍摄屏幕截图,然后使用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);
}
});
还有这样的Screenshot类:
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
答案 0 :(得分:0)
由于默认情况下Android将无法识别不带扩展名的图像,因此您应在上面的意图中将.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);
}
});