Brief introduction
- screenrecord is a shell command
- Supports Android 4.4(API level 19) above
- Supports video format: mp4
Some restrictions
Some devices may not be able to record directly because the resolution is too high. If you encounter this problem, try specifying a lower resolution Screen rotation during recording is not supported. If rotation occurs during recording, the picture may be cut off Sound will not be recorded while video is being recorded
Adb pull /dev/graphics/fb0
adb pull /dev/graphics/fb0 fb.raw adb pull /dev/fb0 fb.raw ffmpeg -vcodec rawvideo -f rawvideo -pix_fmt rgb32 -s X:Y -i fb.raw -f image2 -vcodec png ss.png
Adb shell screencap
Android 4.0
adb shell screencap -p /sdcard/screen.png adb pull /sdcard/screen.png adb shell rm /sdcard/screen.png
w/o adb pull
adb shell screencap -p | perl -pe 's/x0Dx0A/x0A/g' > screen.png adb shell screencap -p | perl -pi -e 's/rn/n/g' > screen.png
This (w/o adb pull) is faster than saving the screen capture image to device sd card then pull/read it from that card and transfer it to PC via USB.
The former way takes a couple of seconds and the latter usually takes less than a sec.
Android take screenshot on rooted device
UPDATE There are a number of other posts asking how to get a Screenshot in android but none seemed to have a full answer of how to do so. Originally I posted this as a question due to a particular issue I was running into while attempting to open a stream to the Frame Buffer. Now I’ve swapped over to dumping the Frame Buffer to a file so I’ve updated my post to show how I got there. For reference (and acknowledgement), I found the command to send the FrameBuffer to a file from this post (unfortunately he didn’t provide how he got to that point). I’m just missing how to turn the raw data I pulled from the Frame Buffer into an actual image file.
My intention was to take a full dump of the actual screen on an Android Device. The only way I could find to do so without using the adb bridge was to directly access the Frame Buffer of the system. Obviously this approach will require root privileges on the device and for the app running it! Fortunately for my purposes I have control over how the Device is set up and having the device rooted with root privileges provided to my application is feasible. My testing is currently being done on an old Droid running 2.2.3.
I found my first hints of how to approach it from https://huaweidevices.ru/a/6970338/1446554. After a bit more research I found another article that describes how to properly run shell commands as root. They were using it to execute a reboot, I use it to send the current frame buffer to an actual file. My current testing has only gotten as far as doing this via ADB and in a basic Activity (each being provided root). I will be doing further testing from a Service running in the background, updates to come! Here is my entire test activity that can export the current screen to a file:
public class ScreenshotterActivity extends Activity { public static final String TAG = "ScreenShotter"; private Button _SSButton; private PullScreenAsyncTask _Puller; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); _SSButton = (Button)findViewById(R.id.main_screenshotButton); _SSButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { if (_Puller != null) return; //TODO: Verify that external storage is available! Could always use internal instead... _Puller = new PullScreenAsyncTask(); _Puller.execute((Void[])null); } }); } private void runSuShellCommand(String cmd) { Runtime runtime = Runtime.getRuntime(); Process proc = null; OutputStreamWriter osw = null; StringBuilder sbstdOut = new StringBuilder(); StringBuilder sbstdErr = new StringBuilder(); try { // Run Script proc = runtime.exec("su"); osw = new OutputStreamWriter(proc.getOutputStream()); osw.write(cmd); osw.flush(); osw.close(); } catch (IOException ex) { ex.printStackTrace(); } finally { if (osw != null) { try { osw.close(); } catch (IOException e) { e.printStackTrace(); } } } try { if (proc != null) proc.waitFor(); } catch (InterruptedException e) { e.printStackTrace(); } sbstdOut.append(readBufferedReader(new InputStreamReader(proc.getInputStream()))); sbstdErr.append(readBufferedReader(new InputStreamReader(proc.getErrorStream()))); } private String readBufferedReader(InputStreamReader input) { BufferedReader reader = new BufferedReader(input); StringBuilder found = new StringBuilder(); String currLine = null; String sep = System.getProperty("line.separator"); try { // Read it all in, line by line. while ((currLine = reader.readLine()) != null) { found.append(currLine); found.append(sep); } } catch (IOException e) { e.printStackTrace(); } finally { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } return null; } class PullScreenAsyncTask extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... params) { File ssDir = new File(Environment.getExternalStorageDirectory(), "/screenshots"); if (ssDir.exists() == false) { Log.i(TAG, "Screenshot directory doesn't already exist, creating..."); if (ssDir.mkdirs() == false) { //TODO: We're kinda screwed... what can be done? Log.w(TAG, "Failed to create directory structure necessary to work with screenshots!"); return null; } } File ss = new File(ssDir, "ss.raw"); if (ss.exists() == true) { ss.delete(); Log.i(TAG, "Deleted old Screenshot file."); } String cmd = "/system/bin/cat /dev/graphics/fb0 > " ss.getAbsolutePath(); runSuShellCommand(cmd); return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); _Puller = null; } }
}This also requires adding the android.permission.WRITE_EXTERNAL_STORAGE permission to the Manifest. As suggested in this post. Otherwise it runs, doesn’t complain, doesn’t create the directories nor the file.
Originally I couldn’t get usable data from the Frame Buffer due to not understanding how to properly run shell commands. Now that I’ve swapped to using the streams for executing commands I can use ‘>’ to send the Frame Buffer’s current data to an actual file…
Ddmlib
mport com.android.ddmlib.AndroidDebugBridge;
import com.android.ddmlib.IDevice;
import com.android.ddmlib.RawImage;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public final String adbLocation = 'PATH_TO_ADB_PLATFORM_TOOLS';
AndroidDebugBridge.init(false);
AndroidDebugBridge bridge = AndroidDebugBridge.createBridge( adbLocation, true);
IDevice device = bridge.getDevices()[0];
RawImage rawImage; try { rawImage = device.getScreenshot(); } catch (IOException ioe) { printAndExit("Unable to get frame buffer: " ioe.getMessage(), true /* terminate */); return; } // device/adb not available? if (rawImage == null) return; if (landscape) { rawImage = rawImage.getRotated(); } // convert raw data to an Image BufferedImage image = new BufferedImage(rawImage.width, rawImage.height, BufferedImage.TYPE_INT_ARGB); int index = 0; int IndexInc = rawImage.bpp &amp;gt;&amp;gt; 3; for (int y = 0 ; y < rawImage.height ; y ) { for (int x = 0 ; x < rawImage.width ; x ) { int value = rawImage.getARGB(index); index = IndexInc; image.setRGB(x, y, value); } } if (!ImageIO.write(image, "png", new File(filepath))) { throw new IOException("Failed to find png writer"); }Directly speak to adb server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("localhost", 5037))
s.send("x%s" % (len("framebuffer:"), "framebuffer:"))
s.recv(4096) # ret should be "OKAY", 4096 is just a buffer size
s.recv(52) # ret should be struct fbinfo
f = open('fb.raw', 'w')
while True: data = s.recv(4096*16) # real fb data if data == "": break f.write(data)
f.closeDisplay log on command line
Parameter: — verbose
-----.Enter the command above to see this information.
Main display is 1080x1920 @59.16fps (orientation=0)
The max width/height supported by codec is 1920x1088
Configuring recorder for1088x1920 video/avc at4.00Mbps
Content area is 1080x1920 atoffset x=4 y=0Time limit reached
Encoder stopping; recorded 133 frames in10secondsStopping encoder and muxer
Executing: /system/bin/am broadcast -a android.intent.action.MEDIA_SCANNER_SCAN_FILE -d file:
Broadcasting: Intent { act=android.intent.action.MEDIA_SCANNER_SCAN_FILE dat=file:
Broadcast completed: result=0Export video:
adb pull /sdcard/demo.mp4 Description: Export video to current directory
Go everywhere to the specified directory
adb pull /sdcard/demo.mp4 F:mvpdemo.mp4First method
//(Save to SDCard)
adb shell /system/bin/screencap -p /sdcard/screenshot.png
adb pull /sdcard/screenshot.png F:\mvp(Save to Computer)If you want to delete pictures from your phone, you can use this command to delete them
adb shell rm /sdcard/screen.pngFirst method:
The screen of your mobile phone is projected to your computer, and you can take screenshots, record videos, or make gif movies using the software on your computer.
Phone screen synchronization all PC, we can use Vysor This chrome plugin, screenshots We can use QQ screenshot shortcut keys Ctrl Alt A to make gif motion maps We can use gif conversion tools LICEcap
Download Address
Limit recording time:
Parameter: — time-limit
adb shell screenrecord Description: Limit video recording time to 10s, if not, default 180s
Making gif motion pictures
utilize LICEcap Convert.
Off-topic topic
The first method is almost as efficient as the second (using the adb command) in capturing and recording videos, but much faster when making gif maps. Why explain the adb command?
One: Let everyone know that there are more ways to broaden their horizons (Ha-ha, I am actually teasing eggs);
2: When using Vysor projection, some mobile phones do not support it. As a second generation, we are sometimes very helpless. It is impossible to say that in order to be able to use Vysor for projection and buy a new mobile phone, at this time, we will step back and use adb command.
Three: As a developer, we still need to learn some common commands.In this way, you can also pretend to be pressing.
CSDN article starting address
Parameter: — bit-rate
adb shell screenrecord Description: Specify a video bit rate of 6Mbps, otherwise default to 4Mbps. You can increase the bit rate to improve video quality or reduce the bit rate to make the file smaller
Pre requisite
- Confirm you have installed monkeyrunner
- it is located at $ANDROID_HOME/tools by default (where ANDROID_HOME should refer to the directory Android SDK is installed).
- (Optional) Confirm installed monkeyrunner is in your $PATH environment variable
Prepare a monkeyrunner script which does the job(taking a screenshot of target device).
# Imports the monkeyrunner modules used by this program
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice
# Connects to the current device, returning a MonkeyDevice object
device = MonkeyRunner.waitForConnection()
# Takes a screenshot
result = device.takeSnapshot()
# Writes the screenshot to a file
result.writeToFile('1.png','png')Then run monkeyrunner.
$ monkeyrunner ss.py
Preface
When we usually write blogs, we often need to take screenshots, record videos, or make gif movies.Today, we rely on it to discuss what methods are available.
Rotate 90 degrees
Parameter: — rotate
Description: This function is experimental, good or bad, do not know
Second method
adb shell screencap -p | sed 's/r$It is important to note that the picture will be saved in the current cmd boot path, screen.png is the name of the picture
Second method:
Use the adb command.Let’s take a look at how to use the adb command for screenshots.
Specify video resolution size:
Parameter: — size
adb shell screenrecord Description: Record video at 1280*720 resolution. For best results, use the size supported by Advanced Video Coding (AVC) on your device if you do not specify the default resolution for using your mobile phone
Specify the bitrate of the video
Start recording command:
adb shell screenrecord /sdcard/demo.mp4Description: Record the screen of your mobile phone in mp4 video format and store it in the sd card of your mobile phone. The default recording time is 180s
View help commands
Parameter: — help
Enter the following command
adb shell screenrecord You will see this information.
Usage: screenrecord [options] <filename>Android screenrecord v1.2. Records the device's display to a .mp4 file.
Options: Set the video size, e.g. "1280x720". Default isthe device's main display resolution (if supported), 1280x720 ifnot. For best results, use a size supported bythe AVC encoder. Set the video bit rate, in bits per second. Value may be specified as bits or megabits, e.g. '4000000' is equivalent to '4M'. Default 4Mbps. Add additional information, such as a timestamp overlay, thatis helpful in videos captured to illustrate bugs. Set the maximum recording time, in seconds. Default / maximum is180. Display interesting information on stdout. Show this message.
Recording continues until Ctrl-C is hit orthetime limit is reached.В кастомных и других прошивках
Во многих кастомных или других прошивках производителей можно сделать скриншот вызвав дополнительное меню зажав кнопку «ВКЛ/ВЫКЛ» и нажать кнопку Скриншот
Для этого вам понадобиться:
1. Компьютер
2. Установить драйвера Android
3. Включить «Отладка по USB»
Жестом на samsung
В новых смартфонах и планшетах Samsung можно выполнить скриншот ребром ладони с одного края к другому
Активировать данную функцию можно перейдя в Настройки -> Управление -> Управление ладонью -> Снимок экрана
Зажимаем кнопки
В большинстве Android (4.0; 4.1; 4.2; 4.3; 4.4; 5.0) устройств выполнить скриншот можно зажав определенные кнопки на устройстве:
- Зажать одновременно кнопку «ВКЛ/ВЫКЛ» «Громкость Вниз» ( НTC, LG, Lenovo, Motorola, Nexus, Xiaomi, Sony, редко Samsung)
- Зажать одновременно кнопку «Домой» «ВКЛ/ВЫКЛ» (Samsung)
- Зажать одновременно кнопку «Домой» кнопку «Назад» (Samsung)
Готовые скриншоты вы найдете в приложение галерея или же файловом менеджере в в следующих папках Pictures/Screenshots илиPictures/ScreenCapture
Использование adb для захвата экрана oh! android
Я пытаюсь как можно быстрее получить скриншот экрана телефона. В настоящее время я делаю:
Однако он слишком медленный и занимает до 3 секунд. Есть ли лучший способ сделать это? Я намерен использовать эту функцию с помощью непереадресованного телефона.
Кроме того, каковы различные аргументы, которые я могу использовать для screencap?
Благодарю.
EDIT (дополнительная информация): я намереваюсь использовать этот метод, чтобы иметь возможность получать живой эфир экрана на моем компьютере. Текущий метод работает, однако он слишком медленный. Я не могу использовать adb shell screenrecord потому что я не смогу получить доступ к видеофайлу во время его записи.
Извините, что вы screencap только простую команду, только принимаете несколько аргументов, но ни один из них не может сэкономить вам время, вот выход -h help.
$ adb shell screencap -h usage: screencap [-hp] [-d display-id] [FILENAME] -h: this message -p: save the file as a png. -d: specify the display id to capture, default 0. If FILENAME ends with .png it will be saved as a png. If FILENAME is not given, the results will be printed to stdout. Помимо команды screencap , есть еще один screenshot команды, я не знаю, почему screenshot был удален с Android 5.0 , но он доступен под Android 4.4 , вы можете проверить источник здесь . Я не делал сравнения между этими двумя командами быстрее, но вы можете попробовать свои силы в реальной среде и принять окончательное решение.
Как сделать скриншот с помощью пк
Сейчас рассмотрим 2 способа — с ручным вводом команды скриншота и автоматизированный.
С вводом команды:
1. Подключаем смартфон или планшет Android к ПК
2. Запускаем программу Adb Run и переходим в меню Manual Command -> ADB
3. Введите команду в командную строку
adb shell screencap -p /sdcard/screenshot.pngпосле чего будет создан скриншот, теперь скопируем его на ПК, вводим команду
С помощью приложений
В версиях Android 2.2 и 2.3 выполнить скриншот можно было только при наличие Root прав и скачав специальное приложение — программы для снятия скриншотов, также данный способ подойдет и для новых версий Android.
Универсальный способ создания скриншот с помощью пк
Данный способ подойдет для пользователей смартфонов и планшетов на которых установлена ОС Android от версии 4.0 и выше (4.0; 4.1; 4.2; 4.3; 4.4; 5.0).
Extend
If you think you have to type this long command adb shell screencap -p | sed’s/r$/’> screen.png every time, for fear of not remembering, there are some ways we can do that.That’s wrapped in alias, which means alias.
Since alias is a linux-specific command, we can no longer use it on windows. If you want to use similar functionality on windows, you can refer to the following blog.
Configuring alias commands on Linux using doskey in Windows
Create alias for the Windows command line
