Advertisement
Guest User

Untitled

a guest
Nov 30th, 2015
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 9.46 KB | None | 0 0
  1. package com.mtsahakis.mediaprojectiondemo;
  2.  
  3. import android.app.Activity;
  4. import android.content.Context;
  5. import android.content.Intent;
  6. import android.graphics.Bitmap;
  7. import android.graphics.Bitmap.CompressFormat;
  8. import android.graphics.PixelFormat;
  9. import android.graphics.Point;
  10. import android.hardware.display.DisplayManager;
  11. import android.hardware.display.VirtualDisplay;
  12. import android.media.Image;
  13. import android.media.ImageReader;
  14. import android.media.projection.MediaProjection;
  15. import android.media.projection.MediaProjectionManager;
  16. import android.os.Bundle;
  17. import android.os.Environment;
  18. import android.os.Handler;
  19. import android.os.Looper;
  20. import android.util.DisplayMetrics;
  21. import android.util.Log;
  22. import android.view.Display;
  23. import android.view.OrientationEventListener;
  24. import android.view.View;
  25. import android.view.View.OnClickListener;
  26. import android.widget.Button;
  27.  
  28. import java.io.File;
  29. import java.io.FileOutputStream;
  30. import java.io.IOException;
  31. import java.nio.ByteBuffer;
  32.  
  33.  
  34. public class ScreenCaptureImageActivity extends Activity {
  35.  
  36.     private static final String TAG = ScreenCaptureImageActivity.class.getName();
  37.     private static final int REQUEST_CODE = 100;
  38.     private static String STORE_DIRECTORY;
  39.     private static int IMAGES_PRODUCED;
  40.     private static final String SCREENCAP_NAME = "screencap";
  41.     private static final int VIRTUAL_DISPLAY_FLAGS = DisplayManager.VIRTUAL_DISPLAY_FLAG_OWN_CONTENT_ONLY | DisplayManager.VIRTUAL_DISPLAY_FLAG_PUBLIC;
  42.     private static MediaProjection sMediaProjection;
  43.  
  44.     private MediaProjectionManager mProjectionManager;
  45.     private ImageReader mImageReader;
  46.     private Handler mHandler;
  47.     private Display mDisplay;
  48.     private VirtualDisplay mVirtualDisplay;
  49.     private int mDensity;
  50.     private int mWidth;
  51.     private int mHeight;
  52.     private int mRotation;
  53.     private OrientationChangeCallback mOrientationChangeCallback;
  54.  
  55.     private class ImageAvailableListener implements ImageReader.OnImageAvailableListener {
  56.         @Override
  57.         public void onImageAvailable(ImageReader reader) {
  58.             Image image = null;
  59.             FileOutputStream fos = null;
  60.             Bitmap bitmap = null;
  61.  
  62.             try {
  63.                 image = mImageReader.acquireLatestImage();
  64.                 if (image != null) {
  65.                     Image.Plane[] planes = image.getPlanes();
  66.                     ByteBuffer buffer = planes[0].getBuffer();
  67.                     int pixelStride = planes[0].getPixelStride();
  68.                     int rowStride = planes[0].getRowStride();
  69.                     int rowPadding = rowStride - pixelStride * mWidth;
  70.  
  71.                     // create bitmap
  72.                     bitmap = Bitmap.createBitmap(mWidth + rowPadding / pixelStride, mHeight, Bitmap.Config.ARGB_8888);
  73.                     bitmap.copyPixelsFromBuffer(buffer);
  74.  
  75.                     // write bitmap to a file
  76.                     fos = new FileOutputStream(STORE_DIRECTORY + "/myscreen_" + IMAGES_PRODUCED + ".png");
  77.                     bitmap.compress(CompressFormat.JPEG, 100, fos);
  78.  
  79.                     IMAGES_PRODUCED++;
  80.                     Log.e(TAG, "captured image: " + IMAGES_PRODUCED);
  81.                 }
  82.  
  83.             } catch (Exception e) {
  84.                 e.printStackTrace();
  85.             } finally {
  86.                 if (fos!=null) {
  87.                     try {
  88.                         fos.close();
  89.                     } catch (IOException ioe) {
  90.                         ioe.printStackTrace();
  91.                     }
  92.                 }
  93.  
  94.                 if (bitmap!=null) {
  95.                     bitmap.recycle();
  96.                 }
  97.  
  98.                 if (image!=null) {
  99.                     image.close();
  100.                 }
  101.             }
  102.         }
  103.     }
  104.  
  105.     private class OrientationChangeCallback extends OrientationEventListener {
  106.         public OrientationChangeCallback(Context context) {
  107.             super(context);
  108.         }
  109.  
  110.         @Override
  111.         public void onOrientationChanged(int orientation) {
  112.             synchronized (this) {
  113.                 final int rotation = mDisplay.getRotation();
  114.                 if (rotation != mRotation) {
  115.                     mRotation = rotation;
  116.                     try {
  117.                         // clean up
  118.                         if(mVirtualDisplay != null) mVirtualDisplay.release();
  119.                         if(mImageReader != null) mImageReader.setOnImageAvailableListener(null, null);
  120.  
  121.                         // re-create virtual display depending on device width / height
  122.                         createVirtualDisplay();
  123.                     } catch (Exception e) {
  124.                         e.printStackTrace();
  125.                     }
  126.                 }
  127.             }
  128.         }
  129.     }
  130.  
  131.     private class MediaProjectionStopCallback extends MediaProjection.Callback {
  132.         @Override
  133.         public void onStop() {
  134.             Log.e("ScreenCapture", "stopping projection.");
  135.             mHandler.post(new Runnable() {
  136.                 @Override
  137.                 public void run() {
  138.                     if(mVirtualDisplay != null) mVirtualDisplay.release();
  139.                     if(mImageReader != null) mImageReader.setOnImageAvailableListener(null, null);
  140.                     if(mOrientationChangeCallback != null) mOrientationChangeCallback.disable();
  141.                     sMediaProjection.unregisterCallback(MediaProjectionStopCallback.this);
  142.                 }
  143.             });
  144.         }
  145.     }
  146.  
  147.     /****************************************** Activity Lifecycle methods ************************/
  148.     @Override
  149.     protected void onCreate(Bundle savedInstanceState) {
  150.         super.onCreate(savedInstanceState);
  151.         setContentView(R.layout.activity_main);
  152.  
  153.         // call for the projection manager
  154.         mProjectionManager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);
  155.  
  156.         // start projection
  157.         Button startButton = (Button)findViewById(R.id.startButton);
  158.         startButton.setOnClickListener(new OnClickListener() {
  159.  
  160.             @Override
  161.             public void onClick(View v) {
  162.                 startProjection();
  163.             }
  164.         });
  165.  
  166.         // stop projection
  167.         Button stopButton = (Button)findViewById(R.id.stopButton);
  168.         stopButton.setOnClickListener(new OnClickListener() {
  169.  
  170.             @Override
  171.             public void onClick(View v) {
  172.                 stopProjection();
  173.             }
  174.         });
  175.  
  176.         // start capture handling thread
  177.         new Thread() {
  178.             @Override
  179.             public void run() {
  180.                 Looper.prepare();
  181.                 mHandler = new Handler();
  182.                 Looper.loop();
  183.             }
  184.         }.start();
  185.     }
  186.  
  187.     @Override
  188.     protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  189.         if (requestCode == REQUEST_CODE) {
  190.             sMediaProjection = mProjectionManager.getMediaProjection(resultCode, data);
  191.  
  192.             if (sMediaProjection != null) {
  193.                 STORE_DIRECTORY = Environment.getExternalStorageDirectory().getAbsolutePath() + "/screenshots/";
  194.                 File storeDirectory = new File(STORE_DIRECTORY);
  195.                 if (!storeDirectory.exists()) {
  196.                     boolean success = storeDirectory.mkdirs();
  197.                     if(!success) {
  198.                         Log.e(TAG, "failed to create file storage directory.");
  199.                         return;
  200.                     }
  201.                 }
  202.  
  203.                 // display metrics
  204.                 DisplayMetrics metrics = getResources().getDisplayMetrics();
  205.                 mDensity = metrics.densityDpi;
  206.                 mDisplay = getWindowManager().getDefaultDisplay();
  207.  
  208.                 // create virtual display depending on device width / height
  209.                 createVirtualDisplay();
  210.  
  211.                 // register orientation change callback
  212.                 mOrientationChangeCallback = new OrientationChangeCallback(this);
  213.                 if (mOrientationChangeCallback.canDetectOrientation()) {
  214.                     mOrientationChangeCallback.enable();
  215.                 }
  216.  
  217.                 // register media projection stop callback
  218.                 sMediaProjection.registerCallback(new MediaProjectionStopCallback(), mHandler);
  219.             }
  220.         }
  221.     }
  222.  
  223.     /****************************************** UI Widget Callbacks *******************************/
  224.     private void startProjection() {
  225.         startActivityForResult(mProjectionManager.createScreenCaptureIntent(), REQUEST_CODE);
  226.     }
  227.  
  228.     private void stopProjection() {
  229.         mHandler.post(new Runnable() {
  230.             @Override
  231.             public void run() {
  232.                 if (sMediaProjection != null) {
  233.                     sMediaProjection.stop();
  234.                 }
  235.             }
  236.         });
  237.     }
  238.  
  239.     /****************************************** Factoring Virtual Display creation ****************/
  240.     private void createVirtualDisplay() {
  241.         // get width and height
  242.         Point size = new Point();
  243.         mDisplay.getSize(size);
  244.         mWidth = size.x;
  245.         mHeight = size.y;
  246.  
  247.         // start capture reader
  248.         mImageReader = ImageReader.newInstance(mWidth, mHeight, PixelFormat.RGBA_8888, 2);
  249.         mVirtualDisplay = sMediaProjection.createVirtualDisplay(SCREENCAP_NAME, mWidth, mHeight, mDensity, VIRTUAL_DISPLAY_FLAGS, mImageReader.getSurface(), null, mHandler);
  250.         mImageReader.setOnImageAvailableListener(new ImageAvailableListener(), mHandler);
  251.     }
  252. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement