What is android lock screen

Как я писал кастомный локер

Привет хабрастарожилам от хабрановичка. Ровно год назад я решил написать кастомный локер (экран блокировки) для моего старичка 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:

Дальше история становится менее интересной, так сказать, будничной. На мой локер можно добавлять ярлыки приложений (здесь все стандартно и просто) и виджеты (а вот этот момент достоин отдельной статьи).

Теперь все стало выглядеть современней:

Источник

Android Lock Screen Settings – How to Change and Disable Screen Lock

Numerous scenarios can be used to best describe when you would need to reset your Android screen lock, but the usual reason for the «why» is to protect your privacy. In any scenario when someone else gets to know your Android screen lock passcode, you forgot your PIN or pattern, or you bought a secondhand device with a screen lock, then the need to reset your Android screen lock will arise.

Therefore, this article proffers lasting solutions to resetting Android screen lock settings at any time and in any situation. You can keep it in your archives as a ‘go-to’ to changing screen locks on Android phones.

3 Points that You Should Be Clear about Google Smart Lock:

1 How to Access Android Lock Screen Settings without Password

Since we carry our phones with us all the time, the possibility of a forgotten or misplaced phone getting fondled and stolen in places we regularly visit is quite high. Therefore, our first line of prevention against such occurrences is to screen lock our Android phones.

If you need a strong line of defense against any evil-doer that can tamper with your Android phone and breach your privacy, then you can choose from the following seven (7) Android screen lock options to secure your device and privacy.

#1.1 Android Lock Screen Settings: Slide/Swipe to Unlock

The «Slide to unlock» or «Swipe screen to unlock» option allows you to slide/swipe your finger on the screen to unlock your device. This Android lock screen settings method prevents your device from displaying the unlock screen when the power button is accidentally pressed. «Slide to unlock» is no longer available in recent Android phones as it stopped with Android 4.2. Now, we have the «Swipe screen to unlock». Slide is when you put your finger on the screen and drag it to the other side or another direction etc.. Swipe on the other hand is basically like sliding but you just quickly slide your finger in another direction but you do not have to do it the full length.

Читайте также:  Как запустить андроид плей

#1.2 Android Lock Screen Settings: Password

Passwords usually comprise letters, numbers, or special characters, but some can be a combination of all the above three (i.e. alphanumeric password). Using a password is probably the best option for your device security. Once you set up a password on your Android phone, it would always be required every time you want to access your phone.

#1.3 Android Lock Screen Settings: PIN

Android PIN (Personal Identification Number) lock is an authentication measure for phones and tablets that require the entry of PIN code before a device is unlocked. Different from a password consisting of numbers, letters and punctuations, a PIN is a combination of numbers only. You can set a 4-digit or 6-digit for your device. This Android lock screen settings authentication measure is the mostly used security protocol by Android device users. Try to avoid obvious numbers such as 1234 or repeating numbers like 1111, or birthday dates.

#1.4 Android Lock Screen Settings: Pattern

The pattern lock is an Android device security measure that allows you to slide your finger over a grid of nine dots in a peculiar pattern to unlock your device. This is one of the more popular screen lock solutions. You have to rember a unique pattern which is probably more vivid than a text or number. The best part of pattern lock is that it offers you different options: with over 6,000 options to choose from.

#1.5 Android Lock Screen Settings: Fingerprint Lock

Fingerprint lock is a type of Android electronic security system that uses fingerprints for biometric authentication to open and grant user access to the features and functionalities of an Android device. Some Android devices do not support this security feature, but for those that support it, the device must have a fingerprint scanner attached to it.

#1.6 Android Lock Screen Settings: Facial Recognition

Facial recognition is a biometric technology that identifies the device owner’s face to unlock an Android device. It analyses the characteristics of a human face without the person having the slightest hint that face recognition is working. It’s praised as the fastest way to unlock a phone since you probably look at your phone when you want to use it.

#1.7 Android Lock Screen Settings: Smart Lock

Android smart lock (Google smart lock) is an Android lock screen settings method and an easy way to gain access to your device that was introduced with Android 5.0 Lollipop. It knows when your Android phone is on your body and keeps the phone unlocked throughout the period you’re carrying it.

2 How to Access Android Lock Screen Settings without Password

Android screen lock prevents unauthorized people and hackers from accessing and using your phone and the information stored in it. But there are times when you may forget your screen lock and need a tool to unlock it. iMyFone LockWiper Android lock screen removal can help you remove Android lock screen in diverse types such as PIN, pattern, password, fingerprint, and facial recognition. You can achieve full phone unlocked within 5 minutes using this tool.

Читайте также:  Установка андроид через twrp

Features of iMyFone LockWiper (Android)

Completely access and reset Android lock screen settings without passwords. lock of your Android phone without passwords.

Efficient in unlocking devices with screen and button faults.

Compatible with over 6,000 Android devices from Samsung, Xiaomi, Huawei, Motorola and ZTE, etc.

Remove lock screen settings from some Samsung devices without data loss.

Unlock FRP Google account verification from Samsung devices.

Steps to Access Android Lock Screen Settings without Passwords

If you forget the password to your screen lock or something goes wrong that you can’t get in your Android device, you can use the professional phone unlocking software — iMyFone LockWiper (Android) to access Andoird lock screen settings without any passwords.

Step 1. Install the software on your Windows computer and select «Remove Screen Lock» from home menu.

Step 2.Connect your Android phone to your computer, and the program will automatically detect your mobile device. Confirm all information shown on the screen, the click «Start Unlock» button to continue.

Step 3. At this stage, the software will install a specific unlocking data package that is suitable for the brand and model of your Android phone.

Step 4. After installing and extracting the package, follow the instructions that appear on your computer screen to complete the unlocking process.

3 How to Customize Android Lock Screen Settings for Widgets, Wallpaper and Timeout

Would you like to customize your Android lock screen settings? It’s completely possible to decide how you want your Android tablet or smartphone to look and function by adjusting a few settings.

Here, we’ll show you how to customize widgets, wallpapers, and timeout on your Android phone.

#3.1 How to Add Widgets on Android Home Screen

With the Lockscreen Widget, you can see the information of your choice quickly without unlocking the screen. When you drag down the widget area (below the clock on the screen), you can see a list of widgets and set, edit or add to the list.

Step 1. On your Home screen, touch and hold an empty space and tap widget.

Step 2. Touch and hold the widget you want to add and slide it to where you want it.

#3.2 How to Add Android Lock Screen Wallpaper

You can easily add new wallpaper on your Android lock screen, home screen, or both. It’s a simple and easy task and the steps are as follows:

Step 1. Tap and press any empty part of your Home screen.

Step 2. Click the wallpaper icon, and select the wallpaper you want to add. Note: you can choose from your gallery or from the list.

Step 3. Choose «Lock Screen» to apply the wallpaper.

#3.3 How to Set Up Android Lock Screen Timeout

If your lock screen timeout period is too short, you can easily readjust it to a period that suits you. Here are the steps to follow:

Step 1. Go to «Setting > Lock Screen and Security> Secure lock settings > Lock automaatically».

Step 2. Choose a preferred screen timeout, and click the Home button to complete the process.

Conclusion

We’ve seen all there is to know about Android lock screen settings: types, options, and how to unlock them. Therefore, we urge you to download the trial version of iMyFone LockWiper (Android) in order to access Android lock screen settings without a password.

By Mike Sangster , to Screen Unlock

Posted on Jan 18, 2020 ( Updated: Feb 04, 2020 )

Home >

  • Tips & Tricks >
  • Screen Unlock >
  • Android Lock Screen Settings – How to Change and Disable Screen Lock
  • Copyright © 2021 Cleverguard Technology Co., Limited. All Rights Reserved

    Источник

    Оцените статью