Android floating window app

Русские Блоги

Реализация плавающего окна Android

Современные технологические новости

19 июня Xiaomi официально объявила, что после неоднократных и тщательных исследований она решила поэтапно реализовать план листинга в Гонконге и Китае, то есть после листинга в Гонконге, затем выбрать возможность листинга в стране, выпустив CDR. В связи с этим SFC выразил уважение к выбору Xiaomi отложить выдачу CDR.

Эта статья из Донг Сяочонг Вклад, делясь знаниями о плавающих окнах в Android, взгляните! Надеюсь, вам всем нравится.

Донг Сяочонг Адрес блога:

Многие приложения теперь используют плавающие окна. Например, когда WeChat находится в видео, нажмите кнопку «Домой», и на экране все еще будет отображаться небольшое видеоокно. Эта функция очень полезна во многих ситуациях. Поэтому сегодня мы реализуем плавающее окно Android и исследуем точки ошибок при реализации плавающего окна.

Интерфейс плагина плавающего окна

Перед реализацией плавающего окна нам нужно знать, через какой интерфейс мы можем поместить элемент управления на экран. Рисование интерфейса Android достигается через сервис WindowMananger. Итак, поскольку мы хотим реализовать плавающее окно, которое может быть на интерфейсе, отличном от нашего собственного приложения, мы должны использовать WindowManager, чтобы «сделать это».

WindowManager реализует интерфейс ViewManager, который можно получить, получив системную службу WINDOW_SERVICE. Интерфейс ViewManager имеет метод addView, и мы используем этот метод для добавления элемента управления плавающим окном на экран.

Настройка разрешения и запрос

Плавающее окно должно отображать элементы управления поверх других приложений. Очевидно, это требует определенных разрешений. Когда API Level> = 23, вам нужно объявить разрешение SYSTEM_ALERT_WINDOW в файле AndroidManefest.xml для рисования элементов управления в других приложениях.

В дополнение к этому разрешению нам также нужно установить разрешение плавающего окна для этого приложения в настройках системы. Это разрешение должно запускать Settings.ACTION_MANAGE_OVERLAY_PERMISSION в приложении, чтобы позволить пользователю вручную устанавливать разрешения.

Настройки LayoutParam

Метод addView в WindowManager имеет два параметра: один — объект управления, который необходимо добавить, а другой — объект WindowManager.LayoutParam.

Здесь необходимо подчеркнуть переменную типа в LayoutParam. Эта переменная используется для указания типа окна. При настройке этой переменной вам нужно обратить внимание на яму, то есть вам нужно адаптироваться к различным версиям системы Android.

До Android 8.0 параметром плавающего окна мог быть TYPE_PHONE, который не является окном приложения и используется для взаимодействия с пользователем.

Android 8.0 изменил поведение системы и API, в том числе приложения, использующие разрешение SYSTEM_ALERT_WINDOW, больше не могут использовать тип окна для отображения окон напоминания над другими приложениями и окнами:

Если вам нужно реализовать окно напоминания над другими приложениями и окнами, это должен быть новый тип TYPE_APPLICATION_OVERLAY. ¡Если плавающее окно типа TYPE_PHONE по-прежнему используется в Android 8.0 и выше, появится следующее сообщение об исключении:

android.view.WindowManager$BadTokenException: Unable to add window [email protected] — permission denied for window type 2002

Позвольте мне объяснить конкретную реализацию плавающего окна. Чтобы отключить плавающее окно от Activity, чтобы плавающее окно могло нормально работать, когда приложение находится в фоновом режиме, здесь мы используем Service, чтобы запустить плавающее окно и служить его логической поддержкой. Перед запуском сервиса вам необходимо определить, разрешено ли открывать плавающее окно в данный момент.

Элемент управления плавающим окном может быть любым подтипом View. Вот пример с самой простой кнопкой.

Хорошо, закончил! Да, верно, это самое простое плавающее окно. Разве это не просто? Давайте посмотрим на эффект.

Конечно, эффект этого плавающего окна только отображается, и он далек от действительно желаемого эффекта. Но основной принцип уже реализован, а остальное — добавить немного функциональности.

Читайте также:  Драйвер zte для андроид

Добавить небольшие функции

Функция перетаскивания

Первое, что я хочу добавить, — это возможность перетаскивать это плавающее окно. Поскольку положение плавающего окна может блокировать информацию, которую мы хотим видеть позади, лучше, если вы можете утащить плавающее окно. В Android обработка сенсорных событий считается самой основной операцией непосредственно в коде.

Здесь следует отметить, что метод обновления макета плавающего окна управления при комментировании кода. Только при вызове этого метода положение плавающего окна изменится. Посмотри на эффект.

Автовоспроизведение фото

Давайте внесем небольшие изменения в плавающее окно, чтобы продемонстрировать немного сложный интерфейс. Здесь мы больше не просто используем элемент управления Button для интерфейса с плавающим окном, но добавляем ImageView в LinearLayout. Файл макета выглядит следующим образом.

Внесите некоторые изменения в место создания плавающего окна.

Мы также хотим, чтобы изображение переключалось каждые две секунды, поэтому давайте создадим механизм для регулярного переключения изображений.

Посмотрите на эффект автоматического воспроизведения картинок в плавающем окне.

Видео виджет

Давайте посмотрим на наиболее часто используемую функцию плавающих окон: маленькие видеоокна. Например, когда WeChat выходит из интерфейса во время видео, видео будет отображаться в виде небольшого окна. Здесь я сначала использую MediaPlay и SurfaceView для воспроизведения сетевого видео для имитации эффекта. Реализация в основном такая же, как у проигрывателя картинок выше, за исключением того, что элементы управления и соответствующая логика воспроизведения изменены. Файл макета аналогичен изображенному выше проигрывателю изображений, за исключением того, что ImageView заменен на SurfaceView. Создать плавающее окно управления.

Хорошо, давайте иметь печальное «Сокровище» с Марса.

Выше приведена реализация плавающего окна Android и некоторых небольших простых приложений. Это можно суммировать как следующие шаги:

Декларация и применение приложения

Элементы управления, необходимые для создания плавающих окон

Добавить элементы управления в `WindowManager`

Обновите макет WindowManager, если это необходимо

Яма, которая должна быть замечена, является проблемой адаптации версии LayoutParams.type.

Адрес проекта следующий:

добро пожаловатьДолгое нажатие -> Определите QR-код на картинке

Илиотсканируйте этоСледуйте за моим публичным аккаунтом

Источник

#3 Floating Windows on Android: Permissions

Learn how to use floating windows in your Android apps. The third lesson teaches you how to ask users for required permissions.

Have you ever wondered how to make those floating windows used by Facebook Heads and other apps? Have you ever wanted to use the same technology in your app? It’s easy, and I will guide you through the whole process.

I’m the author of Floating Apps; the first app of its kind on Google Play and the most popular one with over 8 million downloads. After 6 years of the development of the app, I know a bit about it. It’s sometimes tricky, and I spent months reading documentation and Android source code and experimenting. I received feedback from tens of thousands of users and see various issues on different phones with different Android versions.

Here’s what I learned along the way.

Before reading this article, it’s recommended to go through Floating Windows on Android 2: Foreground Service.

In this article, I will teach you how to ask users for special permission that is required for the floating technology to work.

SYSTEM_ALERT_WINDOW 🔗

For the floating technology to work, we need to define SYSTEM_ALERT_WINDOW in AndroidManifest.xml . Adding this single line is enough:

This permission was initially meant to provide a mechanism for showing system windows – small notifications, error messages, call-in-progress overlays, etc. However, with a bit of effort, we can use it for our floating windows.

Draw Over Other Apps 🔗

The previous step with altering AndroidManifest.xml is not enough. To show floating windows, we need special permission called Draw over other apps. On some phones, it may have a different name. For example, on some Xiaomi phones, it’s Popup permission.

As it’s special permission, we need to point the user to a particular screen in the phone’s settings and manually enable it. Fortunately, there is a way to check for the permission status to implement decent logic for requesting it from the user.

Keep in mind that anytime in the future, the permission may be revoked for the app and so it’s necessary to do periodic checks. For this reason, we create an activity to ask for permission. We can start this activity from anywhere — from other activities as well as from the foreground service.

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

First, let’s add two small helper methods for checking whether the permission is granted or not

Using these two methods, we can add a check for permission into onStartCommand method of our FloatingService introduced in the previous article.

Of course, we need to add our new activity to the AndroidManifest.xml . No extra care is necessary.

And finally, here goes the full source code of the permission activity:

Android 5 & Older 🔗

Everything described above is valid on Android 6 and newer. On Android 5 and older devices, there is no mechanism for obtaining the state of the permission nor the standard mechanism for asking the user to grant it.

Based on my experience, on the majority of older devices, permission is enabled by default. Also, Android 5 is now obsolete enough, so it’s not a concern.

The very first version of Floating Apps was developed for then recent Android 2.3.3, and before Android 6 took over, it was a bit of pain for us .

Unsupported Devices 🔗

On a few devices, this permission is not accessible and can only be enabled through ADB. The same situation applies to some custom ROMs.

Also, on some specific devices such as Android TV boxes, this permission may not be available at all, and the floating technology won’t work.

However, this is my experience gathered from running Floating Apps on about 11.000 different devices, and there is mostly no problem with Draw over other apps. So don’t worry much about it.

Results 🔗

The animation below demonstrates how permission is acquired.

Source Code 🔗

The whole source code for this article is available on Github.

Stay Tuned 🔗

Eager to learn more about Android development? Follow me (@vaclavhodek) and Localazy (@localazy) on Twitter, or like Localazy on Facebook.

The Series 🔗

This article is part of the Floating Windows on Android series.

Источник

#2 Floating Windows on Android: Foreground Service

Learn how to use floating windows in your Android apps. The second lesson teaches you how to create a long-running foreground service.

Have you ever wondered how to make those floating windows used by Facebook Heads and other apps? Have you ever wanted to use the same technology in your app? It’s easy, and I will guide you through the whole process.

I’m the author of Floating Apps; the first app of its kind on Google Play and the most popular one with over 8 million downloads. After 6 years of the development of the app, I know a bit about it. It’s sometimes tricky, and I spent months reading documentation and Android source code and experimenting. I received feedback from tens of thousands of users and see various issues on different phones with different Android versions.

Here’s what I learned along the way.

Before reading this article, it’s recommended to go through Floating Windows on Android 1: Jetpack Compose & Room.

In this article, I teach you how to build the long-running foreground service that is necessary for floating windows and what are the limitations.

The Service 🔗

For the floating technology, it’s necessary to have Service and not Activity. Android can have only one Activity in the foreground and so if we use Activity , other apps would be paused or restarted. And that’s not the desired behavior — we want not to interrupt the current task in any way.

Standard Android services are not designed for long-running operations. They are rather designed to do a task in the background and finish.

To avoid our Service from being killed by the Android system, it’s better to use a foreground service.

For our specific simple app, we use a service that is always running and renders a permanent notification. For your app, having the service running only when there are some floating windows active may be a better approach.

Читайте также:  Что такое timber android

The magic is hidden in the overriding onStartCommand method and returning START_STICKY and START_NOT_STICKY correctly. The source code for this is shown below in this article.

The Limitations 🔗

Show Notification 🔗

A foreground service must show permanent/foreground notification shortly after the service is launched. If we fail to do so, the app is terminated.

On some devices, this may cause occasional crashes as the process may take a bit longer than the hard-coded interval.

Be sure to show the foreground notification as the first thing. The source code for this is shown below in this article.

Also, some users simply dislike the permanent notification being shown, but there is a little we can do about it. They can, on some devices, hide the notification in the phone’s Settings.

Killed On Some Devices 🔗

On some phones and tablets, it’s impossible to avoid the services from being killed thanks to the vendors who are integrating aggressive memory and process management.

There is an excellent website on this topic: Don’t kill my app!

The Permission 🔗

From Android API level 28, extra permission is necessary for foreground services. Add the line below to your AndroidManifest.xml :

The Notification 🔗

From Android O, a permanent notification is required, and with all the experience, I would recommend to use it for older versions too to prevent the service from being killed by Android.

The full source code for the foreground notification, including the code for stopping the service:

Our notification is permanent and cannot be cancelled. It’s clickable and when clicked, it invokes INTENT_COMMAND_NOTE command. Also, the notification has the exit action to invoke INTENT_COMMAND_EXIT.

OnStartCommand 🔗

As mentioned above, the magic behavior of the service is hidden inside onStartCommand . It’s simple:

Service & AndroidManifest 🔗

For our service, we need a record in AndroidManifest.xml file.

Explanation of parameters above:

  • android:excludeFromRecents — Don’t show the service in Recent items screen.
  • android:exported — There is no reason for the service to be accessible from outside the app.
  • android:stopWithTask — Don’t stop the service when the app is terminated, e.g. swiped out of the Recent items screen.

Start Service 🔗

For starting the service, let’s create a small helper method. We need to handle the requirement for Android O and above — to use startForegroundService instead of startService .

In one of the following articles, we will learn how to start our service when the device boot, but for the time being, let’s stick with starting the service when the main app is launched. For this, we just add a single line to our existing MainActivity ’s onCreate method.

Multi Process Approach 🔗

If your floating service is heavy and may cause occasional crashes, you may want to separate it from your app.

You can use android:multiprocess in your AndroidManifest.xml and separate your activities from the service by running them in a different process.

However, keep in mind that using more processes involves extra effort for synchronizing state as activities, and the service would no longer share memory.

Localization 🔗

Above, we added new strings notification_channel_general , notification_text and notification_exit , so be sure to run the Gradle task uploadStrings to upload your translations to the Localazy platform for translating.

A minute after I uploaded my 11 strings, 6 of them are ready in 80 languages!

More information on the importance of app localization was described in Floating Windows on Android 1: Jetpack Compose & Room.

Results 🔗

The animation below demonstrates how the permanent notification is shown when the main app is launched and remains active even if the main app is removed from the Recent items screen.

Source Code 🔗

The whole source code for this article is available on Github.

Stay Tuned 🔗

Eager to learn more about Android development? Follow me (@vaclavhodek) and Localazy (@localazy) on Twitter, or like Localazy on Facebook.

The Series 🔗

This article is part of the Floating Windows on Android series.

Источник

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