Android 如何拍摄屏幕截图并以编程方式共享
我正在用Android制作一个应用程序,在这个程序中,我必须拍摄我的一项活动的截图,并将其作为附件发送出去 我想拍摄当前页面的截图,然后通过电子邮件、蓝牙、Twitter或Facebook进行共享 我的代码如下:Android 如何拍摄屏幕截图并以编程方式共享,android,screenshot,Android,Screenshot,我正在用Android制作一个应用程序,在这个程序中,我必须拍摄我的一项活动的截图,并将其作为附件发送出去 我想拍摄当前页面的截图,然后通过电子邮件、蓝牙、Twitter或Facebook进行共享 我的代码如下: @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menuselected1,
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menuselected1, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.ScreenShot:
try {
takeScreenShot(this);
}
catch (Exception e) {
System.out.println(e);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private static void savePic(Bitmap b, String strFileName) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(strFileName);
if (null != fos) {
b.compress(Bitmap.CompressFormat.PNG, 90, fos);
System.out.println("b is:"+b);
fos.flush();
fos.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void shoot(Activity a,String b) {
//savePic(takeScreenShot(a), "sdcard/xx.png");
savePic(takeScreenShot(a), b);
}
private static Bitmap takeScreenShot(Activity activity) {
View view = activity.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap b1 = view.getDrawingCache();
Rect frame = new Rect();
activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;
int width = activity.getWindowManager().getDefaultDisplay().getWidth();
int height = activity.getWindowManager().getDefaultDisplay()
.getHeight();
// Bitmap b = Bitmap.createBitmap(b1, 0, 25, 320, 455);
Bitmap b = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height
- statusBarHeight);
view.destroyDrawingCache();
return b;
}
如果“当前页面截图”是指“我的一项活动的截图”,您可以安排
如果你说的“当前页面截图”是指“其他人活动的截图”,那么Android SDK不支持这种截图,因为明显的隐私和安全原因。根设备用户可以使用多种技术拍摄屏幕截图。尝试以下方法拍摄当前活动的屏幕截图: 安卓2.2:
private static Bitmap takeScreenShot(Activity activity)
{
View view = activity.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap b1 = view.getDrawingCache();
Rect frame = new Rect();
activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;
DisplayMetrics displaymetrics = new DisplayMetrics();
mContext.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int width = displaymetrics.widthPixels;
int height = displaymetrics.heightPixels;
Bitmap b = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height - statusBarHeight);
view.destroyDrawingCache();
return b;
}
private static void savePic(Bitmap b, String strFileName)
{
FileOutputStream fos = null;
try
{
fos = new FileOutputStream(strFileName);
if (null != fos)
{
b.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.flush();
fos.close();
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
1。创建共享按钮
我想在操作栏中显示我的,所以我创建了一个share_menu.xml文件:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/share_item"
app:showAsAction="always|withText"
android:title="Share"
android:icon="@drawable/share_icon"
android:actionProviderClass=
"android.widget.ShareActionProvider" />
</menu>
如果使用片段执行此操作,则必须在onCreate()
中添加:
setHasOptionsMenu(true);
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
3。设置按钮操作/回调/onclick
这就是分享的开始
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.share_item){
Bitmap bm = screenShot(this.getView());
File file = saveBitmap(bm, "mantis_image.png");
Log.i("chase", "filepath: "+file.getAbsolutePath());
Uri uri = Uri.fromFile(new File(file.getAbsolutePath()));
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_TEXT, "Check out my app.");
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
shareIntent.setType("image/*");
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(shareIntent, "share via"));
}
return super.onOptionsItemSelected(item);
}
请注意,这调用了两个神奇的方法:
屏幕截图():
private Bitmap screenShot(View view) {
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(),view.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return bitmap;
}
private static File saveBitmap(Bitmap bm, String fileName){
final String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Screenshots";
File dir = new File(path);
if(!dir.exists())
dir.mkdirs();
File file = new File(dir, fileName);
try {
FileOutputStream fOut = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 90, fOut);
fOut.flush();
fOut.close();
} catch (Exception e) {
e.printStackTrace();
}
return file;
}
重要
在您的AndroidManifest.xml
中,您必须添加:
setHasOptionsMenu(true);
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
或者屏幕截图不会被保存,gmail会认为你试图附加一个空文件
另外,很多所谓的答案都说使用
“*/*”
作为shareIntent.setType()
,但这会造成facebook共享的问题,因此最好将其保留为“image/*”
这就是我捕获屏幕并共享它的方式。如果你感兴趣的话,请看一看
public Bitmap takeScreenshot() {
View rootView = findViewById(android.R.id.content).getRootView();
rootView.setDrawingCacheEnabled(true);
return rootView.getDrawingCache();
}
以及将位图图像保存到外部存储器的方法:
public void saveBitmap(Bitmap bitmap) {
File imagePath = new File(Environment.getExternalStorageDirectory() + "/screenshot.png");
FileOutputStream fos;
try {
fos = new FileOutputStream(imagePath);
bitmap.compress(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);
}}
有关详细信息,请参见:Kotlin完整解决方案代码及权限检查: 1-使用这个漂亮的库拍摄java/Kotlin/Rx功能的屏幕截图,添加库依赖项: 2-必须检查所有android版本的兼容性权限:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(
Manifest.permission.WRITE_EXTERNAL_STORAGE
) != PackageManager.PERMISSION_GRANTED
) { // Needs permission so request it
DeviceUtil.showAlertMsg(this, GeneralDicModel.shareMsgScreenShot!!)
requestPermissions(
arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE
) //callback result to onRequestPermissionsResult
} else { //Has got the permission before or doesn't need
screenShotAndShareIt()
}
3-检查权限结果:
override fun onRequestPermissionsResult(
requestCode: Int, permissions: Array<out String>,
grantResults: IntArray
) {
when (requestCode) {
PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE -> {
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
screenShotAndShareIt()
} else {
// toast("Permission must be granted in order to save scrrenshot file")
}
}
}
}
5-声明此变量:
val PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 100
6-不要忘记将此权限添加到AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
我想用它来截图我的活动为什么不在Eclipse中使用DDMS并连接手机?我知道这不是一个“代码解决方案”,但你的问题听起来确实有点奇怪。我正在开发android2.2,我使用了你的代码,但它没有显示任何内容,这意味着我想知道图像存储在电话中的位置。建议用缓冲流包装输出流。这仅适用于根设备,它对无根设备有效吗?这在棉花糖中不起作用。你知道如何在棉花糖中解决这个问题吗。对于kitkat,它工作得很好。@VarshaVijayvargiya,我没有尝试过,但是有权限,请注意,在android M中,您必须在运行时询问权限。
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>