【发布时间】:2015-07-31 15:31:30
【问题描述】:
我想以编程方式截取屏幕截图并使用 ShareActionProvider 共享它,而无需请求“android.permission.WRITE_EXTERNAL_STORAGE”权限。 我正在尝试这样做,因为我想避免在不是绝对必要的情况下请求权限,并且能够处理没有外部存储的设备。
我成功地将屏幕截图发送到一些应用程序,但至少有一个(Gmail)不会附加我的屏幕截图。 这是我的代码:
...
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
...
MenuItem shareMenuItem = menu.findItem(R.id.action_share);
ShareActionProvider shareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(shareMenuItem);
shareActionProvider.setShareIntent(createShareIntent());
shareActionProvider.setOnShareTargetSelectedListener(new ShareActionProvider.OnShareTargetSelectedListener()
{
@Override
public boolean onShareTargetSelected(ShareActionProvider source, Intent intent)
{
saveScreenshot();
// The return result is ignored. Return false for consistency.
return false;
}
});
}
private Intent createShareIntent() {
// Get the path of the screenshot inside the directory holding application files.
File screenshotFile = new File(getActivity().getApplicationContext().getFilesDir(), SCREENSHOT_NAME);
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("image/jpeg");
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(screenshotFile));
return shareIntent;
}
private void saveScreenshot() {
view.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
view.setDrawingCacheEnabled(false);
// Save on Internal Storage to avoid asking for WRITE_EXTERNAL_STORAGE permission.
FileOutputStream outputStream = null;
try {
// Open a file associated with this Context's application package for writing.
// Make file readable by other apps otherwise it can't be shared.
outputStream = getActivity().getApplicationContext()
.openFileOutput(SCREENSHOT_NAME, Context.MODE_WORLD_READABLE);
bitmap.compress(Bitmap.CompressFormat.JPEG, COMPRESS_QUALITY, outputStream);
outputStream.close();
} catch (IOException e) {
Log.e(LOG_TAG, "Can't save screenshot!", e);
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
Log.e(LOG_TAG, "Can't close the output stream!", e);
}
}
}
}
...
如果我想与 Twitter、Hangouts、Keep、Evernote、Google 的 Inbox 和我测试过的其他应用程序共享,此代码有效,但它不适用于 Gmail。 例如,在 Nexus 6 上,Gmail 给了我一条 Toast 消息,上面写着“Permission denied”,而在 Nexus 4 上,它只是不附加屏幕截图而没有任何错误消息。 日志中没有任何相关内容。 使用类似的东西
screenshotFile.setReadable(true, false);
或
try {
Runtime.getRuntime().exec("chmod 777 " + screenshotFile.getAbsolutePath());
} catch (IOException e) {
Log.e(LOG_TAG, "Can't give permissions to screenshot file!", e);
}
没有区别。
如果我使用 Environment.getExternalStorageDirectory() 将屏幕截图保存在外部存储上并请求“android.permission.WRITE_EXTERNAL_STORAGE”权限,我测试的所有应用都可以正常工作.
如何在不使用外部存储的情况下执行此操作并让所有应用(包括 Gmail)正常运行? 这可能是 Gmail 应用程序的问题吗? 或者您会建议我只请求允许在外部存储上写入并接受我的一些用户可能会抱怨并且某些设备没有 SD 卡的事实吗?
谢谢!
【问题讨论】:
-
deal with devices without external storage.。现在所有的设备都有外部存储。
标签: android permissions screenshot