Sunday, 30 April 2017

Android: Capture screen as snapshot

This blog post is regarding how to capture your android screen as snapshot. This may be one of your requirements during the course of your application development. It is very simple to implement this functionality as follows:

1. On the click of your button or at the event at which you want to capture your screen just use the below method:

void onYourButtonClick() {
        try {
            LinearLayout layout = (LinearLayout) findViewById(R.id.layout);
            // pass your main layout id
            File screenshot = storeScreenShot(layout, "Screen_shot_" + new Date().getTime() + ".jpg");
            // you need to first save the captured image
        } catch (Exception ex) {
            ex.getMessage();
        }
    }

2. Method to save your file:

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

    public static File storeScreenShot(View v, String fileName) {
        Bitmap bm = getScreenShot(v);
        final String dirPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/SC";
        File dir = new File(dirPath);
        if (!dir.exists()) {
            if (!dir.mkdirs()) {
                Log.d("TAG", "Oops! Failed to create directory");
            }
        }
        File file = new File(dirPath, fileName);
        try {
            FileOutputStream fOut = new FileOutputStream(file);
            bm.compress(Bitmap.CompressFormat.PNG, 100, fOut);
            fOut.flush();
            fOut.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }

3. So the file (screenshot) created in step one is your captured screen image file.
You can use this file as per your needs.


That's all.
Share and comment if any issues.

No comments:

Post a Comment