Java Examples for android.media.projection.MediaProjection

The following java examples will help you to understand the usage of android.media.projection.MediaProjection. These source code samples are taken from different open source projects.

Example 1
Project: cw-omnibus-master  File: ScreenshotService.java View source code
private void startCapture() {
    projection = mgr.getMediaProjection(resultCode, resultData);
    it = new ImageTransmogrifier(this);
    MediaProjection.Callback cb = new MediaProjection.Callback() {

        @Override
        public void onStop() {
            vdisplay.release();
        }
    };
    vdisplay = projection.createVirtualDisplay("andshooter", it.getWidth(), it.getHeight(), getResources().getDisplayMetrics().densityDpi, VIRT_DISPLAY_FLAGS, it.getSurface(), null, handler);
    projection.registerCallback(cb, handler);
}
Example 2
Project: FloatingBall-master  File: ScreenShotActivity.java View source code
private void savePic(int resultCode, Intent data) {
    final MediaProjection mediaProjection = mManager.getMediaProjection(resultCode, data);
    if (mediaProjection == null) {
        Log.e("@@", "media projection is null");
        return;
    }
    //ImageFormat.RGB_565
    mVirtualDisplay = mediaProjection.createVirtualDisplay("ndh", Utils.getScreenSize(this).x, Utils.getScreenSize(this).y, Utils.getScreenInfo(this).densityDpi, DisplayManager.VIRTUAL_DISPLAY_FLAG_PUBLIC, mSurface, null, null);
    Handler handler2 = new Handler(getMainLooper());
    handler2.postDelayed(new Runnable() {

        public void run() {
            //capture the screen
            mImage = mImageReader.acquireLatestImage();
            if (mImage == null) {
                Log.d("ndh--", "img==null");
                return;
            }
            int width = mImage.getWidth();
            int height = mImage.getHeight();
            final Image.Plane[] planes = mImage.getPlanes();
            final ByteBuffer buffer = planes[0].getBuffer();
            int pixelStride = planes[0].getPixelStride();
            int rowStride = planes[0].getRowStride();
            int rowPadding = rowStride - pixelStride * width;
            Bitmap bitmap = Bitmap.createBitmap(width + rowPadding / pixelStride, height, Bitmap.Config.ARGB_8888);
            bitmap.copyPixelsFromBuffer(buffer);
            bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height);
            mImage.close();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd_hh_mm_ss");
            String strDate = dateFormat.format(new java.util.Date());
            String pathImage = Environment.getExternalStorageDirectory().getPath() + "/DCIM/";
            String nameImage = pathImage + strDate + ".png";
            if (bitmap != null) {
                try {
                    File dir = new File(pathImage);
                    if (!dir.exists() && !dir.mkdirs()) {
                        //最多创建两次文件夹
                        dir.mkdirs();
                    }
                    File fileImage = new File(nameImage);
                    if (!fileImage.exists() && !fileImage.createNewFile()) {
                        fileImage.createNewFile();
                    }
                    FileOutputStream out = new FileOutputStream(fileImage);
                    if (out != null) {
                        bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
                        out.flush();
                        out.close();
                        Intent media = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                        Uri contentUri = Uri.fromFile(fileImage);
                        media.setData(contentUri);
                        ScreenShotActivity.this.sendBroadcast(media);
                        Toast.makeText(ScreenShotActivity.this, "图片保存成功:" + nameImage, Toast.LENGTH_SHORT).show();
                        mediaProjection.stop();
                        finish();
                    }
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    finish();
                }
            }
        }
    }, 50);
}
Example 3
Project: screenshare-playground-master  File: MainActivity.java View source code
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    String ip = mReceiverIpEditText.getText().toString();
    final SharedPreferences sharedPreferences = getSharedPreferences(PREF_NAME, 0);
    final SharedPreferences.Editor edit = sharedPreferences.edit();
    edit.putString(RECEIVER_IP_KEY, ip);
    edit.commit();
    if (resultCode == RESULT_OK && requestCode == GET_MEDIA_PROJECTION_CODE) {
        try {
            @SuppressWarnings("ResourceType") MediaProjectionManager mediaProjectionManager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);
            final MediaProjection mediaProjection = mediaProjectionManager.getMediaProjection(resultCode, data);
            mEncoderAsyncTask = new EncoderAsyncTask(this, mediaProjection, mMediaCodecFactory);
            mEncoderAsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
            mSenderAsyncTask = new SenderAsyncTask(ip);
            mSenderAsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        } catch (IOException e) {
            mStartButton.setEnabled(false);
            mStartButton.setText(getString(R.string.mediacodec_error));
            e.printStackTrace();
        }
    }
}
Example 4
Project: ScreenRecordingSample-master  File: ScreenRecorderService.java View source code
/**
	 * start screen recording as .mp4 file
	 * @param intent
	 */
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void startScreenRecord(final Intent intent) {
    if (DEBUG)
        Log.v(TAG, "startScreenRecord:sMuxer=" + sMuxer);
    synchronized (sSync) {
        if (sMuxer == null) {
            final int resultCode = intent.getIntExtra(EXTRA_RESULT_CODE, 0);
            // get MediaProjection
            final MediaProjection projection = mMediaProjectionManager.getMediaProjection(resultCode, intent);
            if (projection != null) {
                final DisplayMetrics metrics = getResources().getDisplayMetrics();
                int width = metrics.widthPixels;
                int height = metrics.heightPixels;
                if (width > height) {
                    // 横長
                    final float scale_x = width / 1920f;
                    final float scale_y = height / 1080f;
                    final float scale = Math.max(scale_x, scale_y);
                    width = (int) (width / scale);
                    height = (int) (height / scale);
                } else {
                    // 縦長
                    final float scale_x = width / 1080f;
                    final float scale_y = height / 1920f;
                    final float scale = Math.max(scale_x, scale_y);
                    width = (int) (width / scale);
                    height = (int) (height / scale);
                }
                if (DEBUG)
                    Log.v(TAG, String.format("startRecording:(%d,%d)(%d,%d)", metrics.widthPixels, metrics.heightPixels, width, height));
                try {
                    // if you record audio only, ".m4a" is also OK.
                    sMuxer = new MediaMuxerWrapper(this, ".mp4");
                    if (true) {
                        // for screen capturing
                        new MediaScreenEncoder(sMuxer, mMediaEncoderListener, projection, width, height, metrics.densityDpi, 800 * 1024, 15);
                    }
                    if (true) {
                        // for audio capturing
                        new MediaAudioEncoder(sMuxer, mMediaEncoderListener);
                    }
                    sMuxer.prepare();
                    sMuxer.startRecording();
                } catch (final IOException e) {
                    Log.e(TAG, "startScreenRecord:", e);
                }
            }
        }
    }
}
Example 5
Project: platform_frameworks_base-master  File: DisplayManagerGlobal.java View source code
public VirtualDisplay createVirtualDisplay(Context context, MediaProjection projection, String name, int width, int height, int densityDpi, Surface surface, int flags, VirtualDisplay.Callback callback, Handler handler) {
    if (TextUtils.isEmpty(name)) {
        throw new IllegalArgumentException("name must be non-null and non-empty");
    }
    if (width <= 0 || height <= 0 || densityDpi <= 0) {
        throw new IllegalArgumentException("width, height, and densityDpi must be " + "greater than 0");
    }
    VirtualDisplayCallback callbackWrapper = new VirtualDisplayCallback(callback, handler);
    IMediaProjection projectionToken = projection != null ? projection.getProjection() : null;
    int displayId;
    try {
        displayId = mDm.createVirtualDisplay(callbackWrapper, projectionToken, context.getPackageName(), name, width, height, densityDpi, surface, flags);
    } catch (RemoteException ex) {
        throw ex.rethrowFromSystemServer();
    }
    if (displayId < 0) {
        Log.e(TAG, "Could not create virtual display: " + name);
        return null;
    }
    Display display = getRealDisplay(displayId);
    if (display == null) {
        Log.wtf(TAG, "Could not obtain display info for newly created " + "virtual display: " + name);
        try {
            mDm.releaseVirtualDisplay(callbackWrapper);
        } catch (RemoteException ex) {
            throw ex.rethrowFromSystemServer();
        }
        return null;
    }
    return new VirtualDisplay(this, display, callbackWrapper, surface);
}
Example 6
Project: DeviceConnect-Android-master  File: HostDeviceScreenCast.java View source code
@Override
protected void onReceiveResult(final int resultCode, final Bundle resultData) {
    if (resultCode == Activity.RESULT_OK) {
        Intent data = resultData.getParcelable(RESULT_DATA);
        if (data != null) {
            mMediaProjection = mManager.getMediaProjection(resultCode, data);
            mMediaProjection.registerCallback(new MediaProjection.Callback() {

                @Override
                public void onStop() {
                    clean();
                }
            }, new Handler(Looper.getMainLooper()));
        }
    }
    if (mMediaProjection != null) {
        callback.onAllowed();
    } else {
        callback.onDisallowed();
    }
}
Example 7
Project: telescope-master  File: TelescopeLayout.java View source code
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public void onReceive(Context context, Intent intent) {
    unregisterRequestCaptureReceiver();
    int resultCode = intent.getIntExtra(RequestCaptureActivity.RESULT_EXTRA_CODE, Activity.RESULT_CANCELED);
    Intent data = intent.getParcelableExtra(RequestCaptureActivity.RESULT_EXTRA_DATA);
    final MediaProjection mediaProjection = projectionManager.getMediaProjection(resultCode, data);
    if (mediaProjection == null) {
        captureCanvasScreenshot();
        return;
    }
    if (intent.getBooleanExtra(RequestCaptureActivity.RESULT_EXTRA_PROMPT_SHOWN, true)) {
        // Delay capture until after the permission dialog is gone.
        postDelayed(new Runnable() {

            @Override
            public void run() {
                captureNativeScreenshot(mediaProjection);
            }
        }, 500);
    } else {
        captureNativeScreenshot(mediaProjection);
    }
}
Example 8
Project: android_frameworks_base-master  File: DisplayManagerGlobal.java View source code
public VirtualDisplay createVirtualDisplay(Context context, MediaProjection projection, String name, int width, int height, int densityDpi, Surface surface, int flags, VirtualDisplay.Callback callback, Handler handler) {
    if (TextUtils.isEmpty(name)) {
        throw new IllegalArgumentException("name must be non-null and non-empty");
    }
    if (width <= 0 || height <= 0 || densityDpi <= 0) {
        throw new IllegalArgumentException("width, height, and densityDpi must be " + "greater than 0");
    }
    VirtualDisplayCallback callbackWrapper = new VirtualDisplayCallback(callback, handler);
    IMediaProjection projectionToken = projection != null ? projection.getProjection() : null;
    int displayId;
    try {
        displayId = mDm.createVirtualDisplay(callbackWrapper, projectionToken, context.getPackageName(), name, width, height, densityDpi, surface, flags);
    } catch (RemoteException ex) {
        throw ex.rethrowFromSystemServer();
    }
    if (displayId < 0) {
        Log.e(TAG, "Could not create virtual display: " + name);
        return null;
    }
    Display display = getRealDisplay(displayId);
    if (display == null) {
        Log.wtf(TAG, "Could not obtain display info for newly created " + "virtual display: " + name);
        try {
            mDm.releaseVirtualDisplay(callbackWrapper);
        } catch (RemoteException ex) {
            throw ex.rethrowFromSystemServer();
        }
        return null;
    }
    return new VirtualDisplay(this, display, callbackWrapper, surface);
}
Example 9
Project: android-sdk-sources-for-api-level-23-master  File: DisplayManagerGlobal.java View source code
public VirtualDisplay createVirtualDisplay(Context context, MediaProjection projection, String name, int width, int height, int densityDpi, Surface surface, int flags, VirtualDisplay.Callback callback, Handler handler) {
    if (TextUtils.isEmpty(name)) {
        throw new IllegalArgumentException("name must be non-null and non-empty");
    }
    if (width <= 0 || height <= 0 || densityDpi <= 0) {
        throw new IllegalArgumentException("width, height, and densityDpi must be " + "greater than 0");
    }
    VirtualDisplayCallback callbackWrapper = new VirtualDisplayCallback(callback, handler);
    IMediaProjection projectionToken = projection != null ? projection.getProjection() : null;
    int displayId;
    try {
        displayId = mDm.createVirtualDisplay(callbackWrapper, projectionToken, context.getPackageName(), name, width, height, densityDpi, surface, flags);
    } catch (RemoteException ex) {
        Log.e(TAG, "Could not create virtual display: " + name, ex);
        return null;
    }
    if (displayId < 0) {
        Log.e(TAG, "Could not create virtual display: " + name);
        return null;
    }
    Display display = getRealDisplay(displayId);
    if (display == null) {
        Log.wtf(TAG, "Could not obtain display info for newly created " + "virtual display: " + name);
        try {
            mDm.releaseVirtualDisplay(callbackWrapper);
        } catch (RemoteException ex) {
        }
        return null;
    }
    return new VirtualDisplay(this, display, callbackWrapper, surface);
}