top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Record my screen in android

+2 votes
303 views

Hi I want to record my screen and save as video file in Android. Note: I don't need the code to work in old versions (I need for Jelly bean and later versions) of android.

Thanks in advance!

posted Jul 22, 2016 by Akshay

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+2 votes
 
Best answer

I assume you don't want to root the device to accomplish this. In that case, you have two options,
1. Using the MediaProjection provided in android API 21 (Lollipop).

private MediaProjectionManager mProjectionManager;
private static final int DISPLAY_WIDTH = 480;
private static final int DISPLAY_HEIGHT = 640;
private MediaProjection mMediaProjection;
private VirtualDisplay mVirtualDisplay;
private MediaProjectionCallback mMediaProjectionCallback;
private ToggleButton mToggleButton;
private MediaRecorder mMediaRecorder;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    DisplayMetrics metrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metrics);
    mScreenDensity = metrics.densityDpi;

    mMediaRecorder = new MediaRecorder();
    initRecorder();
    prepareRecorder();

    mProjectionManager = (MediaProjectionManager) getSystemService
            (Context.MEDIA_PROJECTION_SERVICE);

    mToggleButton = (ToggleButton) findViewById(R.id.toggle);
    mToggleButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onToggleScreenShare(v);
        }
    });

    mMediaProjectionCallback = new MediaProjectionCallback();
}

@Override
public void onDestroy() {
    super.onDestroy();
    if (mMediaProjection != null) {
        mMediaProjection.stop();
        mMediaProjection = null;
    }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode != PERMISSION_CODE) {
        Log.e(TAG, "Unknown request code: " + requestCode);
        return;
    }
    if (resultCode != RESULT_OK) {
        Toast.makeText(this,
                "Screen Cast Permission Denied", Toast.LENGTH_SHORT).show();
        mToggleButton.setChecked(false);
        return;
    }
    mMediaProjection = mProjectionManager.getMediaProjection(resultCode, data);
    mMediaProjection.registerCallback(mMediaProjectionCallback, null);
    mVirtualDisplay = createVirtualDisplay();
    mMediaRecorder.start();
}

public void onToggleScreenShare(View view) {
    if (((ToggleButton) view).isChecked()) {
        shareScreen();
    } else {
        mMediaRecorder.stop();
        mMediaRecorder.reset();
        Log.v(TAG, "Recording Stopped");
        stopScreenSharing();
        initRecorder();
        prepareRecorder();
    }
}

private void shareScreen() {
    if (mMediaProjection == null) {
        startActivityForResult(mProjectionManager.createScreenCaptureIntent(), PERMISSION_CODE);
        return;
    }
    mVirtualDisplay = createVirtualDisplay();
    mMediaRecorder.start();
}

private void stopScreenSharing() {
    if (mVirtualDisplay == null) {
        return;
    }
    mVirtualDisplay.release();
    //mMediaRecorder.release();
}

private VirtualDisplay createVirtualDisplay() {
    return mMediaProjection.createVirtualDisplay("MainActivity",
            DISPLAY_WIDTH, DISPLAY_HEIGHT, mScreenDensity,
            DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
            mMediaRecorder.getSurface(), null /*Callbacks*/, null /*Handler*/);
}

private class MediaProjectionCallback extends MediaProjection.Callback {
    @Override
    public void onStop() {
        if (mToggleButton.isChecked()) {
            mToggleButton.setChecked(false);
            mMediaRecorder.stop();
            mMediaRecorder.reset();
            Log.v(TAG, "Recording Stopped");
            initRecorder();
            prepareRecorder();
        }
        mMediaProjection = null;
        stopScreenSharing();
        Log.i(TAG, "MediaProjection Stopped");
    }
}

private void prepareRecorder() {
    try {
        mMediaRecorder.prepare();
    } catch (IllegalStateException e) {
        e.printStackTrace();
        finish();
    } catch (IOException e) {
        e.printStackTrace();
        finish();
    }
}

private void initRecorder() {
    mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
    mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
    mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
    mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
    mMediaRecorder.setVideoEncodingBitRate(512 * 1000);
    mMediaRecorder.setVideoFrameRate(30);
    mMediaRecorder.setVideoSize(DISPLAY_WIDTH, DISPLAY_HEIGHT);
    mMediaRecorder.setOutputFile("/sdcard/capture.mp4");
}

2. Capturing screen shots continuously, and combine them all to generate video using FFMPEG or any third party libraries.

if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
        File sdCard = Environment.getExternalStorageDirectory();
        File directory = new File(sdCard.getAbsolutePath() + "/ScreenShots");
        directory.mkdirs();

        String filename = "screenshot_" + i + ".png";
        File imageFile = new File(directory, filename);

        // Supports for better capturing (say Keyboard etc) in case your device is rooted
        try {
            Process sh = Runtime.getRuntime().exec("su", null, null);
            OutputStream os = sh.getOutputStream();
            os.write(("/system/bin/screencap -p " + "/sdcard/ScreenShots/" + filename).getBytes("ASCII"));

            os.flush();
            os.close();
            sh.waitFor();
            i++;
        } catch (Exception e) {
            e.printStackTrace();
        }
}

Hope this helps!

answer Jul 22, 2016 by Vinod Kumar K V
Similar Questions
+2 votes

I want to open another application from my application. I know I should use Intent for that, but I am not sure how to use that.

+1 vote

My app cashes when i click submit, it doesnt verify the fields as it should.
It works the way i want to but if i click on submit without entering anything it crashes.

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button addBtn = (Button) findViewById(R.id.addBtn);
        addBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EditText amoutGiven = (EditText) findViewById(R.id.amountG);
                EditText manyPeople = (EditText) findViewById(R.id.mPeople);
                EditText moenyGiven = (EditText) findViewById(R.id.moneyG);
                TextView changeTxt  = (TextView) findViewById(R.id.changeTxt);
                Button nxtBtn     = (Button) findViewById(R.id.nxtBtn);
                Button tryBtn     = (Button) findViewById(R.id.tryBtn);
                android.view.inputmethod.InputMethodManager imm = (android.view.inputmethod.InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);

                if (amoutGiven.getText().length()==0){
                    amoutGiven.setError("This field is required");
                }

                if (manyPeople.getText().length()==0){
                    manyPeople.setError("This field is required");
                }

                if (moenyGiven.getText().length()==0){
                    moenyGiven.setError("This field is required");
                }

                int num1 = Integer.parseInt(amoutGiven.getText().toString());
                int num2 = Integer.parseInt(manyPeople.getText().toString());
                int num3 = Integer.parseInt(moenyGiven.getText().toString());
                int total = num1 * num2;
                int change = num3 - total;

                changeTxt.setVisibility((changeTxt.getVisibility() == View.VISIBLE)
                        ? View.INVISIBLE : View.VISIBLE);

                if (change < 0 ){
                    changeTxt.setText("Your numbers dont add up");
                    tryBtn.setVisibility((tryBtn.getVisibility() == View.VISIBLE)
                            ? View.INVISIBLE : View.VISIBLE);
                    tryBtn.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            startActivity(new Intent(MainActivity.this, MainActivity.class));

                        }
                    });

                }else {

                    changeTxt.setText( "Give Back Change oF: R" + change +"" );
                    nxtBtn.setVisibility((nxtBtn.getVisibility() == View.VISIBLE)
                            ? View.INVISIBLE : View.VISIBLE);
                    nxtBtn.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            startActivity(new Intent(MainActivity.this, MainActivity.class));    
                        }
                    });    
                }    
            }
        });    
    }
}
+2 votes

I've been looking through the sources trying to figure out where it wakes up the screen when I connect and disconnect the charger. Please suggest some hint? I thought it might be NfcService, but I "froze" that service and it still wakes the screen.

+1 vote

How to create an application like button savior that display a button or a group of buttons on the screen when we turn them on PERMANENTLY. I tried to found solution for it but i failed. Please provide the solution for it or any example

...