How to take Screenshot in Android?

368 views.

How to take Screenshot in Android Programatically?

Add Comment
1 Answer(s)
205 views.

JAVA

 


 
package com.example.renown.kotlin;
 
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
 
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
 
public class ScreenShot extends AppCompatActivity{
 File imagePath;
 ImageView imageView;
 @Override
 protected void onCreate(@Nullable Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.screenshot);
 Button button= (Button) findViewById(R.id.screenshotbutton);
 imageView= (ImageView) findViewById(R.id.image);
 
button.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View v) {
 Bitmap bitmap = takeScreenshot();
 saveBitmap(bitmap);
 imageView.setImageBitmap(bitmap);
}
 });
 }
 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);
 }
 }
}

 

screenshot.xml

 

 
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical" android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:background="@color/colorPrimary">
 <Button
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:id="@+id/screenshotbutton"
 android:text="Screen Shot"
 android:layout_gravity="center"
 android:gravity="center"/>
 <ImageView
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:id="@+id/image"/>
</LinearLayout>
 

 

 

 

PERMISSIONS

 

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

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.