Custom android unlock 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:

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

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

Источник

How to Unlock Home Screen Layout [All Phone Model]

This article focuses on providing a detailed guideline on how to unlock home screen layout in situations where you feel to have lost control over your smartphones.

Basil Rathbone

• Filed to: Android Unlock • Proven solutions

Smartphones have turned out to be quite the device that has been wholly consummated by covering billions of people and mounting its importance among the most consumed device throughout the planet. With smartphones, the world has been looking ahead in strengthening its foundations and integrating them within the lives of the people.

For that, many companies have presented state-of-the-art features in their upgraded models. These features are thoroughly tested and configured for the accessibility of the user. Such a feature, though minuscule in magnitude, provides better use of the interface the smartphone provides. Locking or Unlocking your home screen might insignificant, yet it efficiently provides you with the ability to control your applications to a better extent and keep the environment intact.

Читайте также:  Ftp клиенты для андроид

This article focuses on providing a detailed guideline on how to unlock home screen layout in situations where you feel to have lost control over your smartphones. Every smartphone developer has their own taste; thus, this article provides appropriate step-by-step guidance to effectively unlock home screen layout.

Part 1: Lock or Unlock Samsung Home Screen Layout

Samsung smartphones are quite the elite in the Android market. This company is known for presenting a series of different, intuitive Android phones that are integrated with the best of the features, making their use prolific and effective. While having a Samsung smartphone with upgraded features, you can simply lock or unlock the Samsung home screen layout by following a series of simple steps.

Step 1 Open up the «Settings» of your Samsung smartphone.

Step 2 Navigate through the list and open «Display.»

Step 3 Open up «Home Screen» from the following window. The option of «Lock Home Screen Layout» will be available on the list, which can be toggled on and off with the simple button.

Part 2: How to Unlock the Redmi Home Screen Layout

Redmi has been developing its image among the top-grossing smartphone developers in the world. It has been progressively creating impressive mobile models that are both economical and fully jacked with features that are not usually found even in the top-notch mobile models of the other smartphone developing companies.

However, Redmi offers quite a significant feature set inclusive of unlocking the home screen layout. The following step-by-step guide provides a detailed understanding of these features that answers your primary question of ‘how do I unlock my home screen layout’ in Redmi.

Step 1 Have your upgraded Redmi Mobile phone opened and propagate to the «Settings» option of your phone.

Step 2 Navigate through the Settings and locate the option of «Home Screen Option» on the list.

Step 3 You need to tap on the option of «Home Screen Layout.» It is usually represented in the form of a toggle option that can be both enabled and disabled easily from the settings.

Part 3: What about Huawei? How to Unlock Huawei/Honor Home Screen Layout?

If we are observing the actual tycoons of the smartphone industry, Huawei holds a majority of it. Considering the explicit models of Huawei and Honor Series that are being continually upgraded and integrated into the market, these models surely come up with effective features that ensure usability and accessibility to the users.

Considering Huawei and the primary question of how you unlock your home screen layout, it presents you with two different methods that can be adopted for covering the steps. The following guidelines display the two diverse methods along with their steps to help users unlock their home screen layout.

Method 1: Icon Positions of Home Screen Layout

For this method, you need to pinch the two fingers off your hand together on the home screen of your Huawei smartphone. This opens up the «Home Screen Settings» mode on your front. With the settings on the screen, you can simply enable or disable the «Lock Layout.»

Читайте также:  Телефоны самсунг с клавиатурой андроид

Method 2: Using the Settings

This method displays the old school steps that constitute the complete track of opening up the «Settings» of your phone. After having the settings opened, you need to select the option of «Home Screen & Wallpaper» from the list and navigate through the options to select «Home Screen Settings.»

A new window opens on your front. You need to select the option of «Lock Layout» and have it disabled to successfully execute the procedure of unlocking the home screen layout of your Android phone.

Part 4: [One Stop Solution] Is There A Way to Unlock All Types of Phone?

There are hundreds of cases reported daily mentioning the deliberate locking of the phone that makes it equivalent to useless. Many people accidentally lose their passwords or forget them that leave them with a locked phone and nothing to do. You might have come across solutions that lead to some kind of a loss, either of the data or other.

These methods are not recommended by most of the users, leading us to the introduction of third-party platforms that provides simple and efficient structures of unlocking all types of phones. Either going for installing button unlocker fix screen overlay error, you can look over several third-party platforms that look up to ensure user-friendliness and ease-of-use.

dr.fone – Screen Unlock (Android) represents one impeccable platform featuring third-party services that allow you to unlock all types of phones, whether they have been locked through a PIN, a password, or a fingerprint sensor. Before understanding the steps that are involved in unlocking your phone, you need to look over a few reasons that would make you opt for dr.fone.

dr.fone — Screen Unlock (Android)

Unlock Home Screen Layout in One-Click

  • You can remove four different screen lock types, including pattern, PIN, password, or fingerprints from your smartphone.
  • There is no data loss across the phone while removing the lock screen.
  • A very user-friendly platform.
  • You can unlock all kinds of Android phones using its features.

Step1. Install the Software

Launch the application and initiate the «Screen Unlock» function from the home window.

Step2. Connect your Android Phone

After opening the appropriate option, you need to connect your phone through a USB connection. After connecting, tap on the «Unlock Android Screen» button.

Step3. Convert to Download Mode

You need to have your phone skewed into the Download Mode. For that, turn off your phone at first. Following this, hold the ‘Home,’ the ‘Power,’ and the ‘Volume Down’ button simultaneously. Following this, you need to tap on the ‘Volume Up’ key for entering the Download Mode on your smartphone.

Step4. Automatic Execution

With the phone changed into Download Mode, the software automatically has it detected and initiates the recovery. You will be notified over the completion of the task.

Источник

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