- 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 Intents with Chrome
- # Syntax
- # Examples
- # Considerations
- # See also
- Настройки в Android-приложениях
- app_settings 4.1.1
- Metadata
- app_settings #
- Getting Started #
- Platform Specifics #
- Android #
- Example #
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 Intents with Chrome
Published on Friday, February 28, 2014
A little known feature in Android lets you launch apps directly from a web page via an Android Intent. One scenario is launching an app when the user lands on a page, which you can achieve by embedding an iframe in the page with a custom URI-scheme set as the src , as follows: . This works in the Chrome for Android browser, version 18 and earlier. It also works in the Android browser, of course.
The functionality has changed slightly in Chrome for Android, versions 25 and later. It is no longer possible to launch an Android app by setting an iframe’s src attribute. For example, navigating an iframe to a URI with a custom scheme such as paulsawesomeapp:// will not work even if the user has the appropriate app installed. Instead, you should implement a user gesture to launch the app via a custom scheme, or use the «intent:» syntax described in this article.
# Syntax
The best practice is to construct an intent anchor and embed that into the page so the user can launch the app. This gives you a lot more flexibility in controlling how apps are launched, including the ability to pass extra information into the app via Intent Extras.
The basic syntax for an intent-based URI is as follows:
See the Android source for parsing details.
Also, you may choose to specify fallback URL by adding the following string extra:
When an intent could not be resolved, or an external application could not be launched, then the user will be redirected to the fallback URL if it was given.
Some example cases where Chrome does not launch an external application are as follows:
- The intent could not be resolved, i.e., no app can handle the intent.
- JavaScript timer tried to open an application without user gesture.
Note that S. is a way to define string extras. S.browser_fallback_url was chosen for backward compatibility, but the target app won’t see browser_fallback_url value as Chrome removes it.
# Examples
Here’s an intent that launches the Zxing barcode scanner app. It follows the syntax thus:
To launch the Zxing barcode scanner app, you encode your href on the anchor as follows:
See the Android Zxing Manifest, which defines the package and the host.
Also, if fallback URL is specified, the full URL will look like this:
Now the URL will get you to zxing.org if the app could not be found, or the link was triggered from JavaScript without user gesture (or for other cases where we don’t launch an external application.)
# Considerations
If the activity you invoke via an intent contains extras, you can include these as well.
Only activities that have the category filter, android.intent.category.BROWSABLE are able to be invoked using this method as it indicates that the application is safe to open from the Browser.
# See also
And Chrome doesn’t launch an external app for a given Intent URI in the following cases.
- When the Intent URI is redirected from a typed in URL.
- When the Intent URI is initiated without user gesture.
Last updated: Friday, February 28, 2014 • Improve article
Источник
Настройки в Android-приложениях
Интересуюсь темой разработки под Android. Пишу небольшое приложение. Столкнулся с тем, что не до конца понимаю как правильно делать настройки для приложения. Немного погуглил, нашел статью, которая помогла разобраться. Решил перевести статью для русскоязычного сообщества, включив некоторые комментарии к оригиналу.
Настройки являются важной частью приложений на Android (и не только на Android — здесь и далее примечание переводчика). Это очень важно — позволять пользователям изменять настройки приложения, в зависимости от их предпочтений.
Существует два пути работы с настройками в Android — можно создать файл preferences.xml в директории res/xml, либо работать с настройками из кода. В данной статье я покажу как работать с настройками, используя preferences.xml файл.
Элементы настроек имеют следующие атрибуты:
- android:key — имя настройки, по поторому в дальнейшем можно получить ее значение
- android:title — заголовок элемента настройки
- android:summary — краткое описание элемента настройки
- android:defaultValue — значение по умолчанию
В настоящее время доступны следующие типы элементов настроек:
- CheckBoxPreference — простой чекбокс, который возвращает значения true или false.
- ListPreference — группа переключателей (radioGroup), из которых может быть выбран только один элемент. Атрибут android:entries указывает на массив со значениями в res/values/arrays.xml, а android:entryValues на массив с подписями.
- EditTextPreference — показывает диалоговое окно с полем ввода. Возвращает строку в качестве значения.
- RingtonePreference — группа переключателей с выбором рингтона.
- Preference — настройка, работающая как кнопка.
- PreferenceScreen — экран с настройками. Когда один PreferenceScreen вложен в другой, то открывается новый экран с настройками.
- PreferenceCategory — категория настроек.
Экран с настройками | EditTextPreference |
ListPreference | RingtonePreference |
PreferenceScreen |
Скриншоты выше были сгенерированы при помощи следующего preferences.xml:
Атрибуты android:entries и android:entryValues у ListPreference ссылаются на @array/listArray и @array/listValues соответственно. Значения берутся из res/values/arrays.xml, который в нашем случае выглядит следующим образом:
Для того, чтобы показать пользователю экран с настройками, небходимо создать активити, унаследованное от PreferenceActivity. Пример активити:
А вызвать активити с настройками можно, нажав на кнопку на нашем главном активити:
Для того, чтобы использовать выставленными в настройках значениями, добавим метод getPrefs() в главное активити, который нужно вызывать на событии onStart(). Нужно использовать именно onStart(), а не onCreate(), для того, чтобы быть уверенным в том, что используются актуальные настройки, а не те, что были во время создания гланого активити. Наш метод getPrefs() может выглядеть примерно вот так:
Источник
app_settings 4.1.1
Metadata
A Flutter plugin for opening iOS and Android phone settings from an app.
app_settings #
A Flutter plugin for opening iOS and Android phone settings from an app.
Getting Started #
Next, import ‘app_settings.dart’ into your dart code.
Platform Specifics #
The following setting options available on both iOS and Android: openAppSettings, openWIFISettings, openLocationSettings, openSecuritySettings, openBluetoothSettings, openDataRoamingSettings , openDateSettings, openDisplaySettings, openNotificationSettings, openSoundSettings, openInternalStorageSettings, openBatteryOptimizationSettings
TIP: If using Objective-C for iOS in your project, you will need to add use_frameworks! to your Runner project podfile in order to use this Swift plugin:
All options open the current ‘app’ settings section if there are settings defined. If no current settings are defined for the app the iPhone Settings Screen will be displayed.
Android #
Each option will open and display the exact corresponding system settings screen: WIFI, Location, or Security, etc.
Using the openAppSettings option will open the current ‘app’ settings for the running app.
In some cases, to access directly the Bluetooth window, you will need to provide access permissions in the android/app/src/main/AndroidManifest.xml
Example #
Example implementation using a raised button ‘onPressed’ event.
Источник