title: How to record screen and take screenshots, using Android API?
body: <h2>Background</h2>
  
  <p>Android got a new API on Kitkat and Lollipop, to video capture the screen. You can do it either via the ADB tool or via code (starting from Lollipop).</p>
  
  <p>Ever since the new API was out, many apps came to that use this feature, allowing to record the screen, and Microsoft even made its own Google-Now-On-tap competitor app.</p>
  
  <p>Using ADB, you can use:</p>
  
  <pre><code>adb shell screenrecord /sdcard/video.mp4 
  </code></pre>
  
  <p>You can even do it from within Android Studio itself.</p>
  
  <h2>The problem</h2>
  
  <p>I can't find any tutorial or explanation about how to do it using the API, meaning in code.</p>
  
  <h2>What I've found</h2>
  
  <p>The only place I've found is the documentations (<a href="https://developer.android.com/about/versions/android-5.0.html#UI" rel="noreferrer"><strong>here</strong></a>, under "Screen capturing and sharing"), telling me this:</p>
  
  <blockquote>
    <p>Android 5.0 lets you add screen capturing and screen sharing
    capabilities to your app with the new android.media.projection APIs.
    This functionality is useful, for example, if you want to enable
    screen sharing in a video conferencing app.</p>
    
    <p>The new <code>createVirtualDisplay()</code> method allows your app to capture the
    contents of the main screen (the default display) into a Surface
    object, which your app can then send across the network. The API only
    allows capturing non-secure screen content, and not system audio. To
    begin screen capturing, your app must first request the user’s
    permission by launching a screen capture dialog using an Intent
    obtained through the <code>createScreenCaptureIntent()</code> method.</p>
    
    <p>For an example of how to use the new APIs, see the MediaProjectionDemo
    class in the sample project.</p>
  </blockquote>
  
  <p>Thing is, I can't find any "MediaProjectionDemo" sample. Instead, I've found "Screen Capture" sample, but I don't understand how it works, as when I've run it, all I've seen is a blinking screen and I don't think it saves the video to a file. The sample seems very buggy.</p>
  
  <h2>The questions</h2>
  
  <p>How do I perform those actions using the new API:</p>
  
  <ol>
  <li>start recording, optionally including audio (mic/speaker/both).</li>
  <li>stop recording</li>
  <li>take a screenshot instead of video.</li>
  </ol>
  
  <p>Also, how do I customize it (resolution, requested fps, colors, time...)?</p>