- Android Turn on GPS programmatically
- How to open Android Settings programmatically with Java
- Show system settings
- Access specific settings areas
- Constants of android.provider.Settings
- Add the permissions if required
- Русские Блоги
- Автоматически перейти в интерфейс системных настроек автоматически в Android
- Небезопасные разрешения в Android-приложениях
- Самые опасные разрешения
- Разрешения, которые в будущем вы возможно захотите пересмотреть
Android Turn on GPS programmatically
Jan 2, 2019 · 3 min read
In our previous article, we have taught you how to get location using FusedLocationProviderClient and we also mentioned in that article that for using this feature, you need to turn on device GPS manually by redirecting to settings of your device.
Programmatically we can turn on GPS in two ways. First, redirect the user to location settings of a device (by code) or another way is to ask to turn on GPS by GPS dialog using LocationSettingsRequest and SettingsClient.
First method:
By usin g this, the user will be redirected to the Settings page of your device and user has to turn on GPS manually.
Second method:
In this method, we will show you code to turn on GPS using android gms location request and setting clients. Here we provide a custom class GpsUtils.java with a code written in it with method turnGPSOn(). The method has a callback listener to check the current status of GPS. If GPS is already turned on, no further code will be determined and callback revert true as GPS is on. Let’s look at the code below and we will show how to use GpsUtils.java.
SettingsClient class is the main key point for interacting with location-based API. This API makes it easy for an app to ensure that the device’s system settings are properly configured for the app’s location needs.
LocationSettingsRequest Specifies the types of location services the client is interested in using. Settings will be checked for optimal functionality of all requested services. Use LocationSettingsRequest.Builder to construct this object.
GPS Dialog will be shown for SettingsClient’s failure callback and it will result in an activity’s onActivityResult(). So basically if the user agrees for turn on GPS, we can enable GPS flag in our activity.
and now call GpsUtils class before getting a location.
We recommend you to put this code in onCreate() of your activity. So that, turn on GPS and getting a location works well one by one. And also GPS takes some minor delay to trace your device location.
We have provided code in the previous article to get a location. Thus, we made changes for GPS in that code and republish the same code.
Find code here. Code contains previous article example for getting the current location.
Источник
How to open Android Settings programmatically with Java
Carlos Delgado
Learn how to open dinamically the settings of Android in your app easily
In case your app needs that your user make some changes in the Settings menu i.e to set a default app to open a specific type of files etc, you may like to make this task easier for your user by starting the Settings menu of Android dinamically from your app.
Show system settings
To display the Settings page programmatically, you can use the startActivityForResult method with an Intent object and a constant of the Settings, the following example should open the general settings menu of Android:
The usage of the ACTION_SETTINGS constant with startActivityForResult will show system settings. The Settings provider contains global system-level device preferences.
Access specific settings areas
The following list contains all the constants that provide access to different areas of the settings menu:
Note: not all the constants are available on every Android version. In case you need more information visit the official documentation here.
Constants of android.provider.Settings
Activity Action: Show settings for accessibility modules.
Activity Action: Show add account screen for creating a new account.
Activity Action: Show settings to allow entering/exiting airplane mode.
Activity Action: Show settings to allow configuration of APNs.
Activity Action: Show screen of details about a particular application.
Activity Action: Show settings to allow configuration of application development-related settings.
Activity Action: Show settings to allow configuration of application-related settings.
Activity Action: Show battery saver settings.
Activity Action: Show settings to allow configuration of Bluetooth.
Activity Action: Show settings for video captioning.
Activity Action: Show settings to allow configuration of cast endpoints.
Activity Action: Show settings for selection of 2G/3G.
Activity Action: Show settings to allow configuration of date and time.
Activity Action: Show general device information settings (serial number, software version, phone number, etc.).
Activity Action: Show settings to allow configuration of display.
Activity Action: Show Daydream settings.
Activity Action: Show settings to configure the hardware keyboard.
Activity Action: Show Home selection settings.
Activity Action: Show screen for controlling background data restrictions for a particular application.
Activity Action: Show screen for controlling which apps can ignore battery optimizations.
Activity Action: Show settings to configure input methods, in particular allowing the user to enable input methods.
Activity Action: Show settings to enable/disable input method subtypes.
Activity Action: Show settings for internal storage.
Activity Action: Show settings to allow configuration of locale.
Activity Action: Show settings to allow configuration of current location sources.
Activity Action: Show settings to manage all applications.
Activity Action: Show settings to manage installed applications.
Activity Action: Show Default apps settings.
Activity Action: Show screen for controlling which apps can draw on top of other apps.
Activity Action: Show screen for controlling which apps are allowed to write/modify system settings.
Activity Action: Show settings for memory card storage.
Activity Action: Show settings for selecting the network operator.
Activity Action: Show NFC Sharing settings.
Activity Action: Show NFC Tap & Pay settings
This shows UI that allows the user to configure Tap&Pay settings.
Activity Action: Show NFC settings.
Activity Action: Show Notification listener settings.
Activity Action: Show Do Not Disturb access settings.
Activity Action: Show the top level print settings.
Activity Action: Show settings to allow configuration of privacy options.
Activity Action: Show settings to allow configuration of quick launch shortcuts.
Activity Action: Ask the user to allow an app to ignore battery optimizations (that is, put them on the whitelist of apps shown by ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS ).
Activity Action: Show settings for global search.
Activity Action: Show settings to allow configuration of security and location privacy.
Activity Action: Show system settings.
Activity Action: Show the regulatory information screen for the device.
Activity Action: Show settings to allow configuration of sound and volume.
Activity Action: Show settings to allow configuration of sync settings.
Activity Action: Show settings to control access to usage information.
Activity Action: Show settings to manage the user input dictionary.
Activity Action: Modify Airplane mode settings using a voice command.
Activity Action: Modify Battery Saver mode setting using a voice command.
Activity Action: Modify do not disturb mode settings.
Activity Action: Show settings to configure input methods, in particular allowing the user to enable input methods.
Activity Action: Show settings to allow configuration of VPN.
Activity Action: Show VR listener settings.
Activity Action: Allows user to select current webview implementation.
Activity Action: Show settings to allow configuration of a static IP address for Wi-Fi.
Activity Action: Show settings to allow configuration of Wi-Fi.
Activity Action: Show settings to allow configuration of wireless controls such as Wi-Fi, Bluetooth and Mobile networks.
Activity Extra: Limit available options in launched activity based on the given account types.
Activity Extra: Enable or disable Airplane Mode.
Activity Extra: Limit available options in launched activity based on the given authority.
Activity Extra: Enable or disable Battery saver mode.
Activity Extra: Enable or disable Do Not Disturb mode.
Activity Extra: How many minutes to enable do not disturb mode for.
Activity Category: Show application settings related to usage access.
Metadata key: Reason for needing usage access.
For example, you can open directly the Language Settings of the device (to change language) executing:
With the introduction of new Android APIs, there will be more settings available areas with different constants, read the official documentation of android provider settings here.
Add the permissions if required
For some special areas of the Android Settings, you will need permissions. For example, to open the bluetooth settings you’ll need to add the following bluetooth permissions in your app manifest:
And then you’ll be able to open the bluetooth settings:
Otherwise you’ll get the following exception:
Источник
Русские Блоги
Автоматически перейти в интерфейс системных настроек автоматически в Android
Автоматически перейти в интерфейс системных настроек автоматически в Android
Показать учетную запись Add Создайте экран новой учетной записи. [Проверить перейти к интерфейсу входа в третьи лица, например WECHAT]
Режим полета, беспроводная сеть и интерфейс сети
Интерфейс настроек Jump APN
На основе интерфейса информации о приложении, который переходит в систему
Интерфейс опции Jump Developer
Перейти к интерфейсу списка приложений
Интерфейс настройки Bluetooth для системы Jump
Перейти к интерфейсу настроек мобильной сети
Интерфейс настройки времени прыжков дата
Интерфейс статуса прыжка телефона
Интерфейс дисплея телефона
Язык прыжка и устройство ввода
Интерфейс выбора скачки языка [Многоязычный выбор] [API 11 и выше]
Интерфейс настроек хранения прыжков [Внутреннее хранение]
Настройки хранения прыжков [хранение карты памяти]
Интерфейс выбора языка прыжка, только на английском и китайском
Интерфейс сервисного интерфейса Jump [Управление установленными приложениями. 】
Перейти к настройкам отображения Выберите оператор сети.
Отображение параметров совместного использования NFC. [API 14 и выше]
Показать настройки NFC. Это показывает пользовательский интерфейс, позволяющий NFC повернуть или закрыть. [API 16 и выше]
Перейти к резервной копии и сброшенным интерфейсом
Перейти интерфейс настроек Express Start
Перейти к интерфейсу настройки поиска
Перейти к интерфейсу настройки безопасности
Перейти к интерфейсу настройки
Перейти к интерфейсу звука
Интерфейс синхронизации учетной записи
Перейти к пользователям пользователя словарь
Источник
Небезопасные разрешения в Android-приложениях
Сегодня Android является одной из наиболее популярных мобильных платформ, используемой в смартфонах, планшетах, умных часах, телевизорах и даже автомобилях. Открытость платформы, широчайшее разнообразие используемых версий и реализаций выводит вопрос безопасности на первый план при создании Android-приложений.
Как известно, безопасность обеспечивается системой разрешений доступа на каждом конкретном Android-устройстве. Эта система призвана защищать важные данные и предотвращать несанкционированный доступ к информации или каналам связи.
По умолчанию ни у одного Android-приложения нет разрешения на проведение операций, которые могут повлиять на ОС, личные данные или другие приложения. Однако без подобного разрешения любое приложение станет бесполезным.
Разрешения являются своеобразным фильтром для функционала приложений, и только от пользователя зависит, давать ли доступ к данным во время инсталляции. Проблема в том, что пользователи обычно не читают, к чему именно хочет получить доступ приложение, и, не задумываясь, его разрешают. Такое поведение создаёт предпосылки для злоупотребления личными данными или даже модифицирования ядра.
Здесь мы рассмотрим существующую систему манифестов и разрешений в Android. Файл манифеста содержит информацию о пакете приложения, включая разрешения, поставщиков контента, сервисы, активности и широковещательных приёмников (broadcast receivers).
Пример общей структуры файла манифеста. Цветом выделены запросы на получение разрешений:
Самые опасные разрешения
Чтобы решить, к каким данным можно дать доступ, пользователь должен помнить о предназначении этого приложения. Например, «Зачем игре понадобился доступ к моей адресной книге или разрешение отправлять SMS?» Очевидно, что игры не предполагают отправки SMS. Подобные несоответствия функционала запросам доступа должны настораживать в первую очередь.
Разрешения, которые в будущем вы возможно захотите пересмотреть
- Запрос root-прав. Пользователь с root-правами может управлять системой без каких-либо ограничений. По умолчанию в Android таких прав не даётся, поскольку неопытные пользователи могут натворить бед. Root-права предоставляются процессом под названием “Rooting the Android device”. И если их получает злонамеренное приложение, то оно сможет делать всё, что ему заблагорассудится.
Вот небольшой пример того, как приложение запускает shell-скрипт с правами привилегированного пользователя, чтобы перезагрузить устройство:
С помощью команды su приложение запускается с привилегированными правами, и если устройство рутованно, то оно перезагружается. Если же нет, то появляется сообщение:
Чтобы запросить доступ к root:
нужно добавить в файл манифеста строку:
Запрос разрешения на чтение и запись личных данных. Если вы хотите, чтобы пользователи не переживали за свои личные данные, то не используйте в манифесте подобные запросы:
Разрешения, связанные с финансовыми расходами. Некоторые разрешения, бездумно предоставленные пользователями, могут стоить им денег. Чаще всего это отправка SMS/MMS и совершение голосовых вызовов. Причём происходить это может в фоновом режиме, без вызова стандартного телефонного приложения.
Запрос на отправку сообщений:
Запрос на совершение звонков:
Простой пример отправки SMS:
Обратите внимание, что данный код будет работать только в том случае, если соответствующий запрос содержится в файле манифеста:
Доступ к данным геолокации. Если пользователь разрешит, то приложение в любое время сможет получать информацию о:
- примерном местоположении пользователя согласно данным базовых станций и точек Wi-Fi;
- точном местоположении пользователя согласно данным GPS, базовых станций и Wi-Fi.
Запрос доступа к данным о примерном местоположении:
Запрос доступа к данным о точном местоположении:
Вот как осуществляется получение данных о точном местоположении:
Не забывайте, что работоспособность данного кода зависит от наличия соответствующего запроса в файле манифеста.
Java-класс MainActivity внедряет LocationListener для получения нужных данных от устройства. Запрос текущего местоположения осуществляется вызовом requestLocationUpdates() в методе onCreate() . Когда местоположение изменяется, то для получения новых данных вызывается onLocationChanged() . Если GPS-данные недоступны, то вызывается метод onProviderDisabled(), передающий приложению информацию о местоположении.
Доступ к аудио- и видео. Если пользователь даёт такие разрешения, то он рискует тем, что его будут прослушивать или использовать камеру смартфона для слежки. Запросы доступа в файле манифеста:
Установка пакетов. Если дать такое разрешение, то приложение сможет устанавливать дополнительные пакеты без ведома пользователя.
Остановка фоновых процессов. Данное разрешение позволяет приложению вызывать killBackgroundProcesses(String), с чьей помощью оно может останавливать любые выполняющиеся в фоновом режиме процессы.
Источник