我在做Android的应用程序中,我必须把我的活动之一的屏幕截图,以电子邮件附件。
我想利用当前页面截图,然后通过电子邮件,蓝牙,Twitter或Facebook分享。
我的代码如下:
@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;
}
Answer 1:
试试这个采取当前活动的截图:
Android 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();
}
}
Answer 2:
如果“当前页面截图”你的意思是“我的截图活动之一的”,你可以安排使您的Views
为位图支持的Canvas
,然后从位图保存图像 。
如果“当前页面截图”你的意思是“别人的活动的屏幕截图”,即不是由Android SDK的支持,显而易见的隐私和安全方面的原因。 有迹象表明,植根设备的用户可以用它来采取截图的各种技术。
Answer 3:
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>
这与我的share_icon和文本操作栏中添加一个按钮。
2.添加共享菜单到你的活动(或片段)
我做了这个片段里面,所以我说下面的代码片段,我的文件。 如果你是一个活动里面,那么你覆盖public boolean onCreateOptionsMenu(Menu menu)
来代替。
@Override
public void onCreateOptionsMenu(
Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.share_menu, menu);
}
如果你是一个片段这样做,然后在onCreate()
您必须添加:
setHasOptionsMenu(true);
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
,你必须添加:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
或截图将不会被保存,和Gmail会认为你试图附加一个空文件。
此外,很多,所以答案说用"*/*"
为shareIntent.setType()
但是这将创建与Facebook共享的问题,所以最好把它作为"image/*"
。
Answer 4:
这是我拍摄的画面和分享。 看一看,如果你有兴趣。
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);
}}
看多: https://www.youtube.com/watch?v=LRCRNvzamwY&feature=youtu.be
Answer 5:
科特林完整的解决方案代码权限检查:
1 -使用这个漂亮的图书馆采取截屏与Java /科特林/接收功能,增加库的依赖关系: InstaCapture GitHub的链接
implementation "com.github.tarek360:instacapture:2.0.1"
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")
}
}
}
}
4- Func键呼吁采取截图与由意向分享:
fun screenShotAndShareIt() {
Instacapture.capture(this, object : SimpleScreenCapturingListener() {
override fun onCaptureComplete(bitmap: Bitmap) {
val state = Environment.getExternalStorageState()
if (Environment.MEDIA_MOUNTED == state) {
val path: String = Environment.getExternalStorageDirectory().toString()
val picDir = File(path.plus("/myPic"))
if (!picDir.exists()) {
picDir.mkdir()
}
var bitmapScreenShot = bitmap
val fileName = "screenshot" + ".jpg"
val picFile = File(picDir.path.plus("/" + fileName))
try {
picFile.createNewFile()
val picOut = FileOutputStream(picFile)
bitmapScreenShot =
Bitmap.createBitmap(bitmapScreenShot, 0, 0, bitmapScreenShot.width, bitmapScreenShot.height)
val saved: Boolean = bitmapScreenShot.compress(Bitmap.CompressFormat.JPEG, 100, picOut)
if (saved) {
Log.i(
TAG,
"ScreenShotAndShareIt : Image saved to your device Pictures " + "directory! + ${picFile.absolutePath}"
)
} else {
Log.i(TAG, "ScreenShotAndShareIt Error on Save! + ${picFile.absolutePath}")
}
picOut.close()
// share via intent
val intent: Intent = Intent(android.content.Intent.ACTION_SEND)
intent.type = "image/jpeg"
intent.putExtra(Intent.EXTRA_STREAM, Uri.parse(picFile.absolutePath))
startActivity(Intent.createChooser(intent, "Sharing"))
} catch (e: Exception) {
Log.i(TAG, "ScreenShotAndShareIt Error catch : " + e.printStackTrace())
}
} else {
//Error
Log.i(TAG, "ScreenShotAndShareIt Error Environment.MEDIA_MOUNTED == state : " )
}
}
})
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"/>
文章来源: How to take a screenshot and share it programmatically