如何截取当前活动的截图然后分享?

我需要截取Activity (没有标题栏,用户不应该看到截图实际上已被采取),然后通过操作菜单button“共享”分享。 我已经尝试了一些解决scheme,但他们并没有为我工作。 有任何想法吗?

这是我如何抓住屏幕并分享它。 看看你是否有兴趣

首先 ,从当前活动获取根视图:

 View rootView = getWindow().getDecorView().findViewById(android.R.id.content); 

其次 ,抓住根本观点:

  public static Bitmap getScreenShot(View view) { View screenView = view.getRootView(); screenView.setDrawingCacheEnabled(true); Bitmap bitmap = Bitmap.createBitmap(screenView.getDrawingCache()); screenView.setDrawingCacheEnabled(false); return bitmap; } 

第三 ,将Bitmap存储到SD卡中:

 public static void store(Bitmap bm, String fileName){ final static String dirPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Screenshots"; File dir = new File(dirPath); if(!dir.exists()) dir.mkdirs(); File file = new File(dirPath, fileName); try { FileOutputStream fOut = new FileOutputStream(file); bm.compress(Bitmap.CompressFormat.PNG, 85, fOut); fOut.flush(); fOut.close(); } catch (Exception e) { e.printStackTrace(); } } 

最后 ,分享当前Activity的截图:

 private void shareImage(File file){ Uri uri = Uri.fromFile(file); Intent intent = new Intent(); intent.setAction(Intent.ACTION_SEND); intent.setType("image/*"); intent.putExtra(android.content.Intent.EXTRA_SUBJECT, ""); intent.putExtra(android.content.Intent.EXTRA_TEXT, ""); intent.putExtra(Intent.EXTRA_STREAM, uri); try { startActivity(Intent.createChooser(intent, "Share Screenshot")); } catch (ActivityNotFoundException e) { Toast.makeText(context, "No App Available", Toast.LENGTH_SHORT).show(); } } 

我希望你会受到我的代码的启发。

更新:

将以下权限添加到您的AndroidManifest.xml

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> 

因为它创build和访问外部存储中的文件。

点击监听器创build分享button

  share = (Button)findViewById(R.id.share); share.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Bitmap bitmap = takeScreenshot(); saveBitmap(bitmap); shareIt(); } }); 

添加两个方法

  public Bitmap takeScreenshot() { View rootView = findViewById(android.R.id.content).getRootView(); rootView.setDrawingCacheEnabled(true); return rootView.getDrawingCache(); } public void saveBitmap(Bitmap bitmap) { imagePath = new File(Environment.getExternalStorageDirectory() + "/screenshot.png"); FileOutputStream fos; try { fos = new FileOutputStream(imagePath); bitmap.compress(Bitmap.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); } } 

共享屏幕截图。 在这里分享实施

  private void shareIt() { Uri uri = Uri.fromFile(imagePath); Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND); sharingIntent.setType("image/*"); String shareBody = "In Tweecher, My highest score with screen shot"; sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "My Tweecher score"); sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody); sharingIntent.putExtra(Intent.EXTRA_STREAM, uri); startActivity(Intent.createChooser(sharingIntent, "Share via")); } 

您可以通过以下代码获取您在屏幕上看到的视图的位图您可以指定要创build位图的视图。

  public static Bitmap getScreenShot(View view) { View screenView = view.getRootView(); screenView.setDrawingCacheEnabled(true); Bitmap bitmap = Bitmap.createBitmap(screenView.getDrawingCache()); screenView.setDrawingCacheEnabled(false); return bitmap; } 

我不能让静音骑士的答案工作,直到我补充工作

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> 

到我的AndroidManifest.xml

你可以截取你视图的任何部分的截图。你只需要你想要截图的布局的参考。 例如在你的情况下,你想要你的活动的屏幕截图。 假设你的活动根布局是线性布局。

  // find the reference of the layout which screenshot is required LinearLayout LL = (LinearLayout) findViewById(R.id.yourlayout); Bitmap screenshot = getscreenshot(LL); //use this method to get the bitmap private Bitmap getscreenshot(View view) { View v = view; v.setDrawingCacheEnabled(true); Bitmap bitmap = Bitmap.createBitmap(v.getDrawingCache()); return bitmap; } 

为screeshot

  public Bitmap takeScreenshot() { View rootView = findViewById(android.R.id.content).getRootView(); rootView.setDrawingCacheEnabled(true); return rootView.getDrawingCache(); } 

为了保存截图

 private void saveBitmap(Bitmap bitmap) { imagePath = new File(Environment.getExternalStorageDirectory() + "/scrnshot.png"); ////File imagePath FileOutputStream fos; try { fos = new FileOutputStream(imagePath); bitmap.compress(Bitmap.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); } } 

和分享

 private void shareIt() { Uri uri = Uri.fromFile(imagePath); Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND); sharingIntent.setType("image/*"); String shareBody = "My highest score with screen shot"; sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "My Catch score"); sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody); sharingIntent.putExtra(Intent.EXTRA_STREAM, uri); startActivity(Intent.createChooser(sharingIntent, "Share via")); } 

并简化onclick你可以调用这些方法

 shareScoreCatch.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Bitmap bitmap = takeScreenshot(); saveBitmap(bitmap); shareIt(); } }); 

这是我如何抓住屏幕并分享它。 看看你是否有兴趣

 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

对于所有的Xamarin用户:

Xamarin.Android代码:

创build一个外部类(我为每个平台都有一个接口,并且我从android平台实现了下面这三个函数):

  public static Bitmap TakeScreenShot(View view) { View screenView = view.RootView; screenView.DrawingCacheEnabled = true; Bitmap bitmap = Bitmap.CreateBitmap(screenView.DrawingCache); screenView.DrawingCacheEnabled = false; return bitmap; } public static Java.IO.File StoreScreenShot(Bitmap picture) { var folder = Android.OS.Environment.ExternalStorageDirectory + Java.IO.File.Separator + "MyFolderName"; var extFileName = Android.OS.Environment.ExternalStorageDirectory + Java.IO.File.Separator + Guid.NewGuid() + ".jpeg"; try { if (!Directory.Exists(folder)) Directory.CreateDirectory(folder); Java.IO.File file = new Java.IO.File(extFileName); using (var fs = new FileStream(extFileName, FileMode.OpenOrCreate)) { try { picture.Compress(Bitmap.CompressFormat.Jpeg, 100, fs); } finally { fs.Flush(); fs.Close(); } return file; } } catch (UnauthorizedAccessException ex) { Log.Error(LogPriority.Error.ToString(), "-------------------" + ex.Message.ToString()); return null; } catch (Exception ex) { Log.Error(LogPriority.Error.ToString(), "-------------------" + ex.Message.ToString()); return null; } } public static void ShareImage(Java.IO.File file, Activity activity, string appToSend, string subject, string message) { //Push to Whatsapp to send Android.Net.Uri uri = Android.Net.Uri.FromFile(file); Intent i = new Intent(Intent.ActionSendMultiple); i.SetPackage(appToSend); // so that only Whatsapp reacts and not the chooser i.AddFlags(ActivityFlags.GrantReadUriPermission); i.PutExtra(Intent.ExtraSubject, subject); i.PutExtra(Intent.ExtraText, message); i.PutExtra(Intent.ExtraStream, uri); i.SetType("image/*"); try { activity.StartActivity(Intent.CreateChooser(i, "Share Screenshot")); } catch (ActivityNotFoundException ex) { Toast.MakeText(activity.ApplicationContext, "No App Available", ToastLength.Long).Show(); } }` 

现在,从你的Activity中,你可以像这样运行上面的代码:

  RunOnUiThread(() => { //take silent screenshot View rootView = Window.DecorView.FindViewById(Resource.Id.ActivityLayout); Bitmap tmpPic = ShareHandler.TakeScreenShot(this.CurrentFocus); //TakeScreenShot(this); Java.IO.File imageSaved = ShareHandler.StoreScreenShot(tmpPic); if (imageSaved != null) { ShareHandler.ShareImage(imageSaved, this, "com.whatsapp", "", "ScreenShot Taken from: " + "Somewhere"); } }); 

希望这对任何人都有用。

这是我用来截图的东西。 上述解决scheme适用于API <24,但对于API 24及更高版本,还需要其他解决scheme。 我已经在API 15,24和27上testing了这个方法。

我在MainActivity.java中放置了以下方法:

 public class MainActivity { ... String[] permissions = new String[]{"android.permission.READ_EXTERNAL_STORAGE", "android.permission.WRITE_EXTERNAL_STORAGE"}; View sshotView; ... private boolean checkPermission() { List arrayList = new ArrayList(); for (String str : this.permissions) { if (ContextCompat.checkSelfPermission(this, str) != 0) { arrayList.add(str); } } if (arrayList.isEmpty()) { return true; } ActivityCompat.requestPermissions(this, (String[]) arrayList.toArray(new String[arrayList.size()]), 100); return false; } protected void onCreate(Bundle savedInstanceState) { ... this.sshotView = getWindow().getDecorView().findViewById(R.id.parent); ... } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); switch (id) { case R.id.action_shareScreenshot: boolean checkPermission = checkPermission(); Bitmap screenShot = getScreenShot(this.sshotView); if (!checkPermission) { return true; } shareScreenshot(store(screenShot)); return true; case R.id.option2: ... return true; } return false; } private void shareScreenshot(File file) { Parcelable fromFile = FileProvider.getUriForFile(MainActivity.this, BuildConfig.APPLICATION_ID + ".com.redtiger.applehands.provider", file); Intent intent = new Intent(); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); intent.setAction("android.intent.action.SEND"); intent.setType("image/*"); intent.putExtra("android.intent.extra.SUBJECT", XmlPullParser.NO_NAMESPACE); intent.putExtra("android.intent.extra.TEXT", XmlPullParser.NO_NAMESPACE); intent.putExtra("android.intent.extra.STREAM", fromFile); try { startActivity(Intent.createChooser(intent, "Share Screenshot")); } catch (ActivityNotFoundException e) { Toast.makeText(getApplicationContext(), "No Communication Platform Available", Toast.LENGTH_SHORT).show(); } } public static Bitmap getScreenShot(View view) { View rootView = view.getRootView(); rootView.setDrawingCacheEnabled(true); Bitmap createBitmap = Bitmap.createBitmap(rootView.getDrawingCache()); rootView.setDrawingCacheEnabled(false); return createBitmap; public File store(Bitmap bitmap) { String str = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures/Screenshots"; File file = new File(str); if (!file.exists()) { file.mkdirs(); } file = new File(str + "/sshot.png"); try { OutputStream fileOutputStream = new FileOutputStream(file); bitmap.compress(Bitmap.CompressFormat.PNG, 80, fileOutputStream); fileOutputStream.flush(); fileOutputStream.close(); } catch (Exception e) { e.printStackTrace(); Toast.makeText(getApplicationContext(), "External Storage Permission Is Required", Toast.LENGTH_LONG).show(); } return file; } } 

我在AndroidManifest.xml中放置了以下权限和提供者:

 <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.redtiger.applehands"> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.INTERNET" /> <application ... <provider android:name="com.redtiger.applehands.util.GenericFileProvider" android:authorities="${applicationId}.com.redtiger.applehands.provider" android:exported="false" android:grantUriPermissions="true"> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/provider_paths"/> </provider> ... </application> </manifest> 

我创build了一个名为provider_paths.xml的文件(请参阅下面)来指导FileProvider保存截图的位置。 该文件包含一个简单的标记,指向外部目录的根目录。

该文件被放置在资源文件夹res / xml(如果你没有一个xml文件夹在这里,只需创build一个文件在那里)。

provider_paths.xml:

 <?xml version="1.0" encoding="utf-8"?> <paths> <external-path name="external_files" path="."/> </paths> 

节省您的时间,并使用这个android库