How to Capture the Android Device Screen Content

How to capture the android device screen content?

According to this link, it is possible to use ddms in the tools directory of the android sdk to take screen captures.

To do this within an application (and not during development), there are also applications to do so. But as @zed_0xff points out it certainly requires root.

How to programmatically take a screenshot on Android?

Here is the code that allowed my screenshot to be stored on an SD card and used later for whatever your needs are:

First, you need to add a proper permission to save the file:

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

And this is the code (running in an Activity):

private void takeScreenshot() {
Date now = new Date();
android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);

try {
// image naming and path to include sd card appending name you choose for file
String mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg";

// create bitmap screen capture
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);

File imageFile = new File(mPath);

FileOutputStream outputStream = new FileOutputStream(imageFile);
int quality = 100;
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
outputStream.flush();
outputStream.close();

openScreenshot(imageFile);
} catch (Throwable e) {
// Several error may come out with file handling or DOM
e.printStackTrace();
}
}

And this is how you can open the recently generated image:

private void openScreenshot(File imageFile) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(imageFile);
intent.setDataAndType(uri, "image/*");
startActivity(intent);
}

If you want to use this on fragment view then use:

View v1 = getActivity().getWindow().getDecorView().getRootView();

instead of

View v1 = getWindow().getDecorView().getRootView();

on takeScreenshot() function

Note:

This solution doesn't work if your dialog contains a surface view. For details please check the answer to the following question:

Android Take Screenshot of Surface View Shows Black Screen

How to take a screenshot of a current Activity and then share it?

This is how I captured the screen and shared it.

First, get root view from current activity:

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

Second, capture the root view:

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

Third, store the Bitmap into the SDCard:

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();
}
}

At last, share the screenshot of current 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();
}
}

I hope you will be inspired by my codes.

UPDATE:

Add below permissions into your AndroidManifest.xml:

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

Because it creates and accesses files in external storage.

UPDATE:

Starting from Android 7.0 Nougat sharing file links are forbiden. To deal with this you have to implement FileProvider and share "content://" uri not "file://" uri.

Here is a good description how to do it.

How to record screen and take screenshots, using Android API?

First step and the one which Ken White rightly suggested & which you may have already covered is the Example Code provided officially.

I have used their API earlier. I agree screenshot is pretty straight forward. But, screen recording is also under similar lines.

I will answer your questions in 3 sections and will wrap it up with a link. :)


1. Start Video Recording

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();
final int density = metrics.densityDpi;

if (DEBUG) Log.v(TAG, "startRecording:");
try {
sMuxer = new MediaMuxerWrapper(".mp4"); // if you record audio only, ".m4a" is also OK.
if (true) {
// for screen capturing
new MediaScreenEncoder(sMuxer, mMediaEncoderListener,
projection, metrics.widthPixels, metrics.heightPixels, density);
}
if (true) {
// for audio capturing
new MediaAudioEncoder(sMuxer, mMediaEncoderListener);
}
sMuxer.prepare();
sMuxer.startRecording();
} catch (final IOException e) {
Log.e(TAG, "startScreenRecord:", e);
}
}
}
}
}

2. Stop Video Recording

 private void stopScreenRecord() {
if (DEBUG) Log.v(TAG, "stopScreenRecord:sMuxer=" + sMuxer);
synchronized(sSync) {
if (sMuxer != null) {
sMuxer.stopRecording();
sMuxer = null;
// you should not wait here
}
}
}

2.5. Pause and Resume Video Recording

 private void pauseScreenRecord() {
synchronized(sSync) {
if (sMuxer != null) {
sMuxer.pauseRecording();
}
}
}

private void resumeScreenRecord() {
synchronized(sSync) {
if (sMuxer != null) {
sMuxer.resumeRecording();
}
}
}

Hope the code helps. Here is the original link to the code that I referred to and from which this implementation(Video recording) is also derived from.


3. Take screenshot Instead of Video

I think by default its easy to capture the image in bitmap format. You can still go ahead with MediaProjectionDemo example to capture screenshot.

[EDIT] : Code encrypt for screenshot

a. To create virtual display depending on device width / height

mImageReader = ImageReader.newInstance(mWidth, mHeight, PixelFormat.RGBA_8888, 2);
mVirtualDisplay = sMediaProjection.createVirtualDisplay(SCREENCAP_NAME, mWidth, mHeight, mDensity, VIRTUAL_DISPLAY_FLAGS, mImageReader.getSurface(), null, mHandler);
mImageReader.setOnImageAvailableListener(new ImageAvailableListener(), mHandler);

b. Then start the Screen Capture based on an intent or action-

startActivityForResult(mProjectionManager.createScreenCaptureIntent(), REQUEST_CODE);

Stop Media projection-

sMediaProjection.stop();

c. Then convert to image-

//Process the media capture
image = mImageReader.acquireLatestImage();
Image.Plane[] planes = image.getPlanes();
ByteBuffer buffer = planes[0].getBuffer();
int pixelStride = planes[0].getPixelStride();
int rowStride = planes[0].getRowStride();
int rowPadding = rowStride - pixelStride * mWidth;
//Create bitmap
bitmap = Bitmap.createBitmap(mWidth + rowPadding / pixelStride, mHeight, Bitmap.Config.ARGB_8888);
bitmap.copyPixelsFromBuffer(buffer);
//Write Bitmap to file in some path on the phone
fos = new FileOutputStream(STORE_DIRECTORY + "/myscreen_" + IMAGES_PRODUCED + ".png");
bitmap.compress(CompressFormat.PNG, 100, fos);
fos.close();

There are several implementations (full code) of Media Projection API available.
Some other links that can help you in your development-

  1. Video Recording with MediaProjectionManager - website

  2. android-ScreenCapture - github as per android developer's observations :)

  3. screenrecorder - github

  4. Capture and Record Android Screen using MediaProjection APIs - website


Hope it helps :) Happy coding and screen recording!

PS: Can you please tell me the Microsoft app you are talking about? I have not used it. Would like to try it :)

How to take snapshot of device screen programmatically?

I got the answer for my question. Actualy i am getting bitmap as null. but i found the reason and the solution.

View v = findViewById(R.id.attachments_list);
v.setDrawingCacheEnabled(true);
// this is the important code :)
// Without it the view will have a dimension of 0,0 and the bitmap will
// be null
v.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());

v.buildDrawingCache(true);
Bitmap bitmap = Bitmap.createBitmap(v.getDrawingCache());


Related Topics



Leave a reply



Submit