Как я писал кастомный локер
Привет хабрастарожилам от хабрановичка. Ровно год назад я решил написать кастомный локер (экран блокировки) для моего старичка Samsung Galaxy Gio в стиле популярного тогда Samsung Galaxy s3. Какие причины заставили меня это сделать, писать не буду, но добавлю лишь то, что в Google Play я программу не собирался выкладывать и каким-либо другим способом заработать на ней не планировал. Данный пост посвящен последствиям моего решения.
Начну издалека. Многие хвалят Android за открытость и возможность заменить и настроить встроенные программы под свои нужды. Что тут сказать? В сравнении с другими популярными ОС, это, безусловно, так, но если копнуть глубже в архитектуру Android возникают трудности и вопросы. Локскрин (в Android это называется keyguard) как раз и вызывает вопросы: почему Google не поступили с ним, так как с лаунчерами, почему не сделали диалог со всеми доступными на устройстве локерами и с возможностью выбрать нужный по умолчанию? Где-то в глубине мозга тихим нерешительным голосом кто-то отвечает: может быть Google (Android Ink. если быть точнее) поступил так из соображений безопасности. Этот голос вероятно прав и многим разработчикам локеров и мне (скромность не позволила приписать себя к их числу) пришлось изобретать велосипед, и не один.
Изучаем исходники
Начал я с использования одного из плюсов Android – из изучения исходников. Я один из тех консерваторов, которые уже 2,5 года сидят на стоковой прошивке (2.3.6), поэтому и исходники изучал соответствующие. Классы, отвечающие за блокировку экрана, лежат в android.policy.jar, что в system/framework. Первоначальной целью было найти «точку входа», т.е. где и когда вызывается локер. Искал здесь.
В классе PhoneWindowManager.java есть метод screenTurnedOff(int why), который вызывает одноименный метод класса KeyguardViewMediator. Проследив, кто кого вызывает, я нашел метод в классе KeyguardViewManager, создающий непосредственно View стокового локера.
Что ж, все гениальное – просто. Решил повторить этот код для своего приложения и получил ошибку – нет нужного permission. Немного погуглив, добавил следующие разрешения: SYSTEM_ALERT_WINDOW и INTERNAL_SYSTEM_WINDOW. Это не помогло.
Вернулся к изучению класса PhoneWindowManager.java:
Для требуемого окна TYPE_KEYGUARD нужно второе из моих добавленных разрешений. Задней точкой тела начал ощущать, что не все так просто, как я себе представлял. Решено было посмотреть на описание этого permission. Вот выдержка из AndroidManifest.xml пакета framework-res.apk.
Вот она – черная полоса в жизни. Ведь я понимал, «signature» – это значит, что использовать этот пермишн может только пакет, подписанный тем же ключом, что и пакет, выдавший это разрешение (в нашем случае — framework-res.apk). Ладно, достаем инструменты для изготовления велосипедов.
Версия один
Первым решением было использовать activity в качестве локскрина. На stackoverflow советуют использовать следующий код:
Признаюсь, в первых версиях я использовал этот метод. У него есть существенные недостатки: статусбар не блокируется, начиная с версии API11 этот метод не работает.
Решение первого недостатка (переполнениестека опять помогло) следующее. Поверх статусбара с помощью WindowManager рисуется прозрачный View, который перехватывает все TouchEvent. Вот служба, реализующая это:
Второго недостатка для меня не существовало, на Gingerbread данный код работал превосходно. На 4pda, куда я опрометчиво выложил свое творение, пользователи жаловались, что на многих телефонах мой локер сворачивался как обычное приложение. Для них найдено такое решение. В качестве стандартного лаунчера устанавливается пустышка. При нажатии кнопки HOME система вызывает мой лаунчер-пустышку. Если кастомный локер активен, лаунчер сразу же закрывается в методе onCreate(), т.е. визуально нажатие кнопки HOME ни к чему не приводит. Если кастомный локер не активен, мой лаунчер тут же вызывает другой правильный лаунчер, который пользователь указал в настройках.
Вот код пустышки:
Выглядело это следующим образом:
Эти велосипеды ездили долго и хорошо, пока я не решил сделать «правильный» локскрин, и уже в стиле Samsung Galaxy S4.
Версия два
Когда системе необходимо запускать кастомный локер? Очевидно, что при выключении экрана. Создадим службу, регистрирующую BroadcastReceiver, т.к. из манифеста данный фильтр не работает.
Необходимо учесть две особенности:
1. Служба должна быть запущена в момент загрузки устройства. Создадим BroadcastReseiver с IntentFilter «android.intent.action.BOOT_COMPLETED». Есть одно НО: служба при запуске должна отключить стандартную блокировку экрана. Особенностью Android является то, что стандартное окно ввода PIN-кода является частью стокового экрана блокировки. Поэтому служба должна запускаться только когда PIN буден введен.
Максимум, на что хватило моей фантазии:
2. Проанализировав PhoneWindowManager видно, что в метод screenTurnedOff(int why) передается переменная why, принимающая 3 значения:
— экран выключился по истечению таймаута (в этом случае стоковый локер запускается с задержкой),
— экран выключился при срабатывании сенсора приближения (во время телефонного разговора),
— экран выключился при нажатии кнопки.
В моем случае такого разнообразия нет. Поэтому служба мониторит состояние телефона, и при входящем звонке или во время разговора экран не блокируется.
Вот основной код службы:
Идея не использовать activity, а использовать WindowManager была еще сильна. Из пяти типов окон, использующих разрешение SYSTEM_ALERT_WINDOW, мне подошел TYPE_SYSTEM_ALERT. Причем у него были очевидные достоинства: блокировался статусбар (по крайней мере, на Gingerbread) и перехватывалось нажатие кнопки HOME (работает даже на Jelly Bean).
Промежуточным звеном между службой и KeyguardView является класс KeyguardMediator:
Дальше история становится менее интересной, так сказать, будничной. На мой локер можно добавлять ярлыки приложений (здесь все стандартно и просто) и виджеты (а вот этот момент достоин отдельной статьи).
Теперь все стало выглядеть современней:
Источник
Amazing Game
Kamis, 29 Agustus 2019
Android Studio Emulator Lock Screen
The android emulator appears. while the emulator is running, you can run android studio projects and choose the emulator as the target device. you can also drag one or more apks onto the emulator to install them, and then run them. install and add files. to install an apk file on the emulated device, drag an apk file onto the emulator screen.. Android emulator shows nothing but blank screen. android and after that it will show you the lock screen. android.com/studio/run/emulator. I’m trying to develop android applications for the archos 5, using the android_avd emulator skin. unfortunately, when the emulator comes up, it says «screen locked — press menu key to unlock», but.
App lock & folder lock finger print scanner access for
In addition to installing an app through android studio or the emulator ui, set emulated touch screen mode. for example: $ emulator @nexus_5x_api_23 -screen no-touch.. Beginning android: launching the android virtual device. is a device configuration that is run within the android emulator. (to lock the screen at any time,. A full description on everything you need to know about enabling and disabling screen lock android devices.
Источник
Android emulator lock screen
Feel free to ask questions add issues. If I don’t respond to an issue or PR, feel free to ping me or send me DIRECT Message on twitter @thealeksandr. If you create issue it would be nice if you SUBSCRIBE FOR UPDATES. So we can discuss it.
Please support with a Star 😀
7 Update — Bug fixing (November 3, 2019)
- Added code validation for CREATE mode.
Min SDK Version — 15
PFLockScreen — Lock Screen Library for Android Application. Library support pin code and fingerprint authorization for API level 23+.
Add library to your project
Create pin code
Creating lock screen fragment in create mode.
After user created pin code. The library will encode it using Android Key Store and return an encoded string in PFLockScreenFragment.OnPFLockScreenCodeCreateListener. All you have to do is save encoded string somewhere — database, SharedPreferences, Android Account etc.
Show authorization screen
Creating lock screen fragment in authorization mode is same as in creation mode, but instead of MODE_CREATE use MODE_AUTH.
setTitle(String) — set custom string on the top of the screen. setUseFingerprint(boolean) — by default fingerprint button will be shown for all device 23+ with a fingerprint sensor. If you don’t want use fingerprint at all set false. setMode(PFLockScreenMode) — MODE_CREATE or MODE_AUTH. See details above. setCodeLength(int) — set the length of the pin code. By default, length is 4. Minimum length is 4. setLeftButton(String, View.OnClickListener) — set string for the left button and ClickListener.
Check if pin code encryption key exist
An encryption key is needed to encode/decode pin code and stored in Android KeyStore.
Delete pin code encryption key.
You need to delete encryption key if you delete/reset pin code.
Don’t use PFFingerprintPinCodeHelper.getInstance().isPinCodeExist() directly.
Also you can use PFPinCodeViewModel() for the same methods. ViewModel wrapper around PinCodeHelper that returns LiveData objects.
Custom encryption. NEW! NEW! NEW!
Now you can create your custom encryption if for some reasons the one I have doesn’t meet your app requarements:
You need to override java IPFPinCodeHelper interface. That has four methods:
encodePin — method where you encode pin.
checkPin — to check if pin is valid.
delete — deletePinCode and all related stuff.
isPinCodeEncryptionKeyExist — if you have any encryprion keys or something else you’re using to encrpt your key here you check if all keys you need are exists. Haven’t beed deleted or anyting. This method is only for your own logic. Basically to check if you’re code can be decrypted.
All methods take callback as a parameter in case if you want implement something async like server side or whatever.
You can customize buttons, backgrounds, etc. To do that, use attributes in your activity theme:
pf_key_button — style object for key buttons (0-9) pf_lock_screen — style object for the background. Use it to set custom background. pf_fingerprint_button — style object for fingerprint button. You can set custom drawable, paddings, etc. pf_delete_button — style object for delete/backspace button. You can set custom drawable, paddings, etc. pf_code_view — style object to customize code view. (The view from the top of the screen). The view itself is set of check boxes. To customize it use a custom selector with checked states.
pf_title (NEW) — style object for title.
pf_next (NEW) — style object for next button.
pf_hint (NEW) — style object for hint button (Can’t remember).
If you want just a bit correct an existing styles you can override:
The only important thing you can’t change right now is the size of keys. But it’s coming.
Feel free to ask questions add issues. If I don’t respond to an issue or PR, feel free to ping me or send me DM on twitter @thealeksandr. If you create issue it would be nice if you subscribe for updates. So we can discuss it.
Источник
Android emulator lock screen
This application provides display and control of Android devices connected via USB (or over TCP/IP). It does not require any root access. It works on GNU/Linux, Windows and macOS.
- lightness: native, displays only the device screen
- performance: 30
120fps, depending on the device
70ms
low startup time:
1 second to display the first image
Its features include:
The Android device requires at least API 21 (Android 5.0).
Make sure you enabled adb debugging on your device(s).
On some devices, you also need to enable an additional option to control it using keyboard and mouse.
- Linux: apt install scrcpy
- Windows: download
- macOS: brew install scrcpy
On Debian and Ubuntu:
A Snap package is available: scrcpy .
For Fedora, a COPR package is available: scrcpy .
For Gentoo, an Ebuild is available: scrcpy/ .
For Windows, for simplicity, a prebuilt archive with all the dependencies (including adb ) is available:
It is also available in Chocolatey:
The application is available in Homebrew. Just install it:
You need adb , accessible from your PATH . If you don’t have it yet:
It’s also available in MacPorts, which sets up adb for you:
Plug an Android device, and execute:
It accepts command-line arguments, listed by:
Sometimes, it is useful to mirror an Android device at a lower definition to increase performance.
To limit both the width and height to some value (e.g. 1024):
The other dimension is computed to that the device aspect ratio is preserved. That way, a device in 1920×1080 will be mirrored at 1024×576.
The default bit-rate is 8 Mbps. To change the video bitrate (e.g. to 2 Mbps):
Limit frame rate
The capture frame rate can be limited:
This is officially supported since Android 10, but may work on earlier versions.
The device screen may be cropped to mirror only part of the screen.
This is useful for example to mirror only one eye of the Oculus Go:
If —max-size is also specified, resizing is applied after cropping.
Lock video orientation
To lock the orientation of the mirroring:
This affects recording orientation.
Some devices have more than one encoder, and some of them may cause issues or crash. It is possible to select a different encoder:
To list the available encoders, you could pass an invalid encoder name, the error will give the available encoders:
It is possible to record the screen while mirroring:
To disable mirroring while recording:
«Skipped frames» are recorded, even if they are not displayed in real time (for performance reasons). Frames are timestamped on the device, so packet delay variation does not impact the recorded file.
On Linux, it is possible to send the video stream to a v4l2 loopback device, so that the Android device can be opened like a webcam by any v4l2-capable tool.
The module v4l2loopback must be installed:
To create a v4l2 device:
This will create a new video device in /dev/videoN , where N is an integer (more options are available to create several devices or devices with specific IDs).
To list the enabled devices:
To start scrcpy using a v4l2 sink:
(replace N by the device ID, check with ls /dev/video* )
Once enabled, you can open your video stream with a v4l2-capable tool:
For example, you could capture the video within OBS.
It is possible to add buffering. This increases latency but reduces jitter (see #2464).
The option is available for display buffering:
Scrcpy uses adb to communicate with the device, and adb can connect to a device over TCP/IP. The device must be connected on the same network as the computer.
An option —tcpip allows to configure the connection automatically. There are two variants.
If the device (accessible at 192.168.1.1 in this example) already listens on a port (typically 5555) for incoming adb connections, then run:
If adb TCP/IP mode is disabled on the device (or if you don’t know the IP address), connect the device over USB, then run:
It will automatically find the device IP address, enable TCP/IP mode, then connect to the device before starting.
Alternatively, it is possible to enable the TCP/IP connection manually using adb :
Connect the device to the same Wi-Fi as your computer.
Get your device IP address, in Settings → About phone → Status, or by executing this command:
Enable adb over TCP/IP on your device: adb tcpip 5555 .
Unplug your device.
Connect to your device: adb connect DEVICE_IP:5555 (replace DEVICE_IP ).
Run scrcpy as usual.
It may be useful to decrease the bit-rate and the definition:
If several devices are listed in adb devices , you must specify the serial:
If the device is connected over TCP/IP:
You can start several instances of scrcpy for several devices.
Autostart on device connection
To connect to a remote device, it is possible to connect a local adb client to a remote adb server (provided they use the same version of the adb protocol).
Remote ADB server
To connect to a remote ADB server, make the server listen on all interfaces:
Warning: all communications between clients and ADB server are unencrypted.
Suppose that this server is accessible at 192.168.1.2. Then, from another terminal, run scrcpy:
By default, scrcpy uses the local port used for adb forward tunnel establishment (typically 27183 , see —port ). It is also possible to force a different tunnel port (it may be useful in more complex situations, when more redirections are involved):
To communicate with a remote ADB server securely, it is preferable to use a SSH tunnel.
First, make sure the ADB server is running on the remote computer:
Then, establish a SSH tunnel:
From another terminal, run scrcpy:
To avoid enabling remote port forwarding, you could force a forward connection instead (notice the -L instead of -R ):
From another terminal, run scrcpy:
Like for wireless connections, it may be useful to reduce quality:
By default, the window title is the device model. It can be changed:
Position and size
The initial window position and size may be specified:
To disable window decorations:
To keep the scrcpy window always on top:
The app may be started directly in fullscreen:
Fullscreen can then be toggled dynamically with MOD + f .
The window may be rotated:
Possibles values are:
- 0 : no rotation
- 1 : 90 degrees counterclockwise
- 2 : 180 degrees
- 3 : 90 degrees clockwise
The rotation can also be changed dynamically with MOD + ← (left) and MOD + → (right).
Note that scrcpy manages 3 different rotations:
- MOD + r requests the device to switch between portrait and landscape (the current running app may refuse, if it does not support the requested orientation).
- —lock-video-orientation changes the mirroring orientation (the orientation of the video sent from the device to the computer). This affects the recording.
- —rotation (or MOD + ← / MOD + → ) rotates only the window content. This affects only the display, not the recording.
Other mirroring options
To disable controls (everything which can interact with the device: input keys, mouse events, drag&drop files):
If several displays are available, it is possible to select the display to mirror:
The list of display ids can be retrieved by:
The secondary display may only be controlled if the device runs at least Android 10 (otherwise it is mirrored in read-only).
To prevent the device to sleep after some delay when the device is plugged in:
The initial state is restored when scrcpy is closed.
Turn screen off
It is possible to turn the device screen off while mirroring on start with a command-line option:
Or by pressing MOD + o at any time.
To turn it back on, press MOD + Shift + o .
On Android, the POWER button always turns the screen on. For convenience, if POWER is sent via scrcpy (via right-click or MOD + p ), it will force to turn the screen off after a small delay (on a best effort basis). The physical POWER button will still cause the screen to be turned on.
It can also be useful to prevent the device from sleeping:
Power off on close
To turn the device screen off when closing scrcpy:
For presentations, it may be useful to show physical touches (on the physical device).
Android provides this feature in Developers options.
Scrcpy provides an option to enable this feature on start and restore the initial value on exit:
Note that it only shows physical touches (with the finger on the device).
By default, scrcpy does not prevent the screensaver to run on the computer.
Rotate device screen
Press MOD + r to switch between portrait and landscape modes.
Note that it rotates only if the application in foreground supports the requested orientation.
Any time the Android clipboard changes, it is automatically synchronized to the computer clipboard.
Any Ctrl shortcut is forwarded to the device. In particular:
- Ctrl + c typically copies
- Ctrl + x typically cuts
- Ctrl + v typically pastes (after computer-to-device clipboard synchronization)
This typically works as you expect.
The actual behavior depends on the active application though. For example, Termux sends SIGINT on Ctrl + c instead, and K-9 Mail composes a new message.
To copy, cut and paste in such cases (but only supported on Android >= 7):
- MOD + c injects COPY
- MOD + x injects CUT
- MOD + v injects PASTE (after computer-to-device clipboard synchronization)
In addition, MOD + Shift + v allows to inject the computer clipboard text as a sequence of key events. This is useful when the component does not accept text pasting (for example in Termux), but it can break non-ASCII content.
WARNING: Pasting the computer clipboard to the device (either via Ctrl + v or MOD + v ) copies the content into the device clipboard. As a consequence, any Android application could read its content. You should avoid to paste sensitive content (like passwords) that way.
Some devices do not behave as expected when setting the device clipboard programmatically. An option —legacy-paste is provided to change the behavior of Ctrl + v and MOD + v so that they also inject the computer clipboard text as a sequence of key events (the same way as MOD + Shift + v ).
To disable automatic clipboard synchronization, use —no-clipboard-autosync .
To simulate «pinch-to-zoom»: Ctrl +click-and-move.
More precisely, hold Ctrl while pressing the left-click button. Until the left-click button is released, all mouse movements scale and rotate the content (if supported by the app) relative to the center of the screen.
Concretely, scrcpy generates additional touch events from a «virtual finger» at a location inverted through the center of the screen.
Physical keyboard simulation (HID)
By default, scrcpy uses Android key or text injection: it works everywhere, but is limited to ASCII.
On Linux, scrcpy can simulate a physical USB keyboard on Android to provide a better input experience (using USB HID over AOAv2): the virtual keyboard is disabled and it works for all characters and IME.
However, it only works if the device is connected by USB, and is currently only supported on Linux.
To enable this mode:
If it fails for some reason (for example because the device is not connected via USB), it automatically fallbacks to the default mode (with a log in the console). This allows to use the same command line options when connected over USB and TCP/IP.
In this mode, raw key events (scancodes) are sent to the device, independently of the host key mapping. Therefore, if your keyboard layout does not match, it must be configured on the Android device, in Settings → System → Languages and input → Physical keyboard.
This settings page can be started directly:
However, the option is only available when the HID keyboard is enabled (or when a physical keyboard is connected).
Text injection preference
There are two kinds of events generated when typing text:
- key events, signaling that a key is pressed or released;
- text events, signaling that a text has been entered.
By default, letters are injected using key events, so that the keyboard behaves as expected in games (typically for WASD keys).
But this may cause issues. If you encounter such a problem, you can avoid it by:
(but this will break keyboard behavior in games)
On the contrary, you could force to always inject raw key events:
These options have no effect on HID keyboard (all key events are sent as scancodes in this mode).
By default, holding a key down generates repeated key events. This can cause performance problems in some games, where these events are useless anyway.
To avoid forwarding repeated key events:
This option has no effect on HID keyboard (key repeat is handled by Android directly in this mode).
Right-click and middle-click
By default, right-click triggers BACK (or POWER on) and middle-click triggers HOME. To disable these shortcuts and forward the clicks to the device instead:
To install an APK, drag & drop an APK file (ending with .apk ) to the scrcpy window.
There is no visual feedback, a log is printed to the console.
Push file to device
To push a file to /sdcard/Download/ on the device, drag & drop a (non-APK) file to the scrcpy window.
There is no visual feedback, a log is printed to the console.
The target directory can be changed on start:
Audio is not forwarded by scrcpy. Use sndcpy.
In the following list, MOD is the shortcut modifier. By default, it’s (left) Alt or (left) Super .
It can be changed using —shortcut-mod . Possible keys are lctrl , rctrl , lalt , ralt , lsuper and rsuper . For example:
Super is typically the Windows or Cmd key.
Action | Shortcut |
---|---|
Switch fullscreen mode | MOD + f |
Rotate display left | MOD + ← (left) |
Rotate display right | MOD + → (right) |
Resize window to 1:1 (pixel-perfect) | MOD + g |
Resize window to remove black borders | MOD + w | Double-left-click¹ |
Click on HOME | MOD + h | Middle-click |
Click on BACK | MOD + b | Right-click² |
Click on APP_SWITCH | MOD + s | 4th-click³ |
Click on MENU (unlock screen) | MOD + m |
Click on VOLUME_UP | MOD + ↑ (up) |
Click on VOLUME_DOWN | MOD + ↓ (down) |
Click on POWER | MOD + p |
Power on | Right-click² |
Turn device screen off (keep mirroring) | MOD + o |
Turn device screen on | MOD + Shift + o |
Rotate device screen | MOD + r |
Expand notification panel | MOD + n | 5th-click³ |
Expand settings panel | MOD + n + n | Double-5th-click³ |
Collapse panels | MOD + Shift + n |
Copy to clipboard⁴ | MOD + c |
Cut to clipboard⁴ | MOD + x |
Synchronize clipboards and paste⁴ | MOD + v |
Inject computer clipboard text | MOD + Shift + v |
Enable/disable FPS counter (on stdout) | MOD + i |
Pinch-to-zoom | Ctrl +click-and-move |
Drag & drop APK file | Install APK from computer |
Drag & drop non-APK file | Push file to device |
¹Double-click on black borders to remove them.
²Right-click turns the screen on if it was off, presses BACK otherwise.
³4th and 5th mouse buttons, if your mouse has them.
⁴Only on Android >= 7.
Shortcuts with repeated keys are executted by releasing and pressing the key a second time. For example, to execute «Expand settings panel»:
- Press and keep pressing MOD .
- Then double-press n .
- Finally, release MOD .
All Ctrl +key shortcuts are forwarded to the device, so they are handled by the active application.
To use a specific adb binary, configure its path in the environment variable ADB :
To override the path of the scrcpy-server file, configure its path in SCRCPY_SERVER_PATH .
To override the icon, configure its path in SCRCPY_ICON_PATH .
A colleague challenged me to find a name as unpronounceable as gnirehtet.
strcpy copies a string; scrcpy copies a screen.
Источник