- Configuration
- In this document
- See also
- Update channels
- Proxy Settings
- Setting up the Android Studio Proxy
- Android Plugin for Gradle HTTP proxy settings
- SDK Manager HTTP Proxy Settings
- Настройки в Android-приложениях
- What’s the best way to do «application settings» in Android? [closed]
- 1 Answer 1
- How to Code a Settings Screen in an Android App
- Prerequisites
- 1. Create an Android Studio Project
- 2. Creating a PreferenceFragment
- 3. Creating Our Preferences
- Switch Preference
- EditText Preference
- List Preference
- MultiSelect List Preference
- Ringtone Preference
- 4. Creating Setting Groups
- 6. Binding the Preference Summary to the Value Selected
- 7. Retrieving Preference Values
- 8. Bonus: Using Android Studio Templates
- Conclusion
Configuration
In this document
See also
During installation, Android Studio provides wizards and templates that verify your system requirements, such as the Java Development Kit (JDK) and available RAM, and configure default settings, such as an optimized default Android Virtual Device (AVD) emulation and updated system images. This document describes additional configuration settings you may want to use to customize your use of Android Studio.
For specific documentation about emulator and device setup and use, see Managing Virtual Devices, Using Hardware Devices, and OEM USB Drivers.
Update channels
Android Studio provides four update channels to keep Android Studio up-to-date based on your code-level preference:
- Canary channel: Canary builds provide bleeding edge releases, updated about weekly. While these builds do get tested, they are still subject to bugs, as we want people to see what’s new as soon as possible. This is not recommended for production.
- Dev channel: Dev builds are hand-picked older canary builds that survived the test of time. They are updated roughly bi-weekly or monthly.
- Beta channel: Beta builds are used for beta-quality releases before a production release.
- Stable channel: Used for stable, production-ready versions.
By default, Android Studio uses the Stable channel. Use File > Settings > Appearance & Behavior System Settings > Updates to change your channel setting.
Proxy Settings
Proxies serve as intermediary connection points between HTTP clients and web servers that add security and privacy to internet connections.
To support running Android Studio behind a firewall, set the proxy settings for the Android Studio IDE and the SDK Manager. Use the Android Studio IDE HTTP Proxy settings page to set the HTTP proxy settings for Android Studio. The SDK Manager has a separate HTTP Proxy settings page.
When running the Android Plugin for Gradle from the command line or on machines where Android Studio is not installed, such as continuous integration servers, set the proxy settings in the Gradle build file.
Note: After the initial installation of the Android Studio bundle, Android Studio can run with internet access or off-line. However, Android Studio requires an internet connection for Setup Wizard synchronization, 3rd-party library access, access to remote repositories, Gradle initialization and synchronization, and Android Studio version updates.
Setting up the Android Studio Proxy
Android Studio supports HTTP proxy settings so you can run Android Studio behind a firewall or secure network. To set the HTTP proxy settings in Android Studio:
- From the main menu choose File > Settings > Appearance & Behavior — System Settings — HTTP Proxy.
- In Android Studio, open the IDE Settings dialog.
- On Windows and Linux, choose File > Settings > IDE Setting — HTTP Proxy.
- On Mac, choose Android Studio > Preferences > IDE Setting — HTTP Proxy.
The HTTP Proxy page appears.
- Select auto-detection to use an auto-configuration URL to configure the proxy settings or manual to enter each of the settings. For a detailed explanation of these settings, see HTTP Proxy.
- Click Apply to enable the proxy settings.
Android Plugin for Gradle HTTP proxy settings
For application-specific HTTP proxy settings, set the proxy settings in the build.gradle file as required for each application module.
For project-wide HTTP proxy settings, set the proxy settings in the gradle/gradle.properties file.
For information about using Gradle properties for proxy settings, see the Gradle User Guide.
Note: When using Android Studio, the settings in the Android Studio IDE HTTP proxy settings page override the HTTP proxy settings in the gradle.properties file.
SDK Manager HTTP Proxy Settings
SDK Manager proxy settings enable proxy internet access for Android package and library updates from SDK Manager packages.
To set the SDK Manager settings for proxy internet access, start the SDK Manager and open the SDK Manager page.
- On Windows, select Tools > Options from the menu bar.
- On Mac and Linux, choose Tools > Options from the system menu bar.
The Android SDK Manager page appears. Enter the settings and click Apply.
Источник
Настройки в 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() может выглядеть примерно вот так:
Источник
What’s the best way to do «application settings» in Android? [closed]
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago .
I’d like to store some application settings (like the URL of an API, and some settings for testing) for an Android application.
I mostly work as a .NET developer, so I’m used to using the file app.config for this purpose. What’s a good way to do it in Android?
1 Answer 1
Many applications may provide a way to capture user preferences on the settings of a specific application or an activity. For supporting this, Android provides a simple set of APIs.
Preferences are typically name value pairs. They can be stored as “Shared Preferences” across various activities in an application (note currently it cannot be shared across processes). Or it can be something that needs to be stored specific to an activity.
Shared Preferences: The shared preferences can be used by all the components (activities, services etc) off the applications.
Activity handled preferences: These preferences can only be used with in the activity and can not be used by other components of the application.
Shared Preferences:
The shared preferences are managed with the help of getSharedPreferences method of the Context class. The preferences are stored in a default file(1) or you can specify a file name(2) to be used to refer to the preferences.
(1) Here is how you get the instance when you specify the file name
MODE_PRIVATE is the operating mode for the preferences. It is the default mode and means the created file will be accessed by only the calling application. Other two mode supported are MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE . In MODE_WORLD_READABLE other application can read the created file but can not modify it. In case of MODE_WORLD_WRITEABLE other applications also have write permissions for the created file.
(2) The recommended way is to use by the default mode, without specifying the file name
Finally, once you have the preferences instance, here is how you can retrieve the stored values from the preferences:
To store values in the preference file SharedPreference.Editor object has to be used. Editor is the nested interface of the SharedPreference class.
Editor also support methods like remove() and clear() to delete the preference value from the file.
Activity Preferences:
The shared preferences can be used by other application components. But if you do not need to share the preferences with other components and want to have activities private preferences. You can do that with the help of getPreferences() method of the activity. The getPreference method uses the getSharedPreferences() method with the name of the activity class for the preference file name.
Following is the code to get preferences
The code to store values is also same as in case of shared preferences.
You can also use other methods like storing the activity state in database. Note Android also contains a package called android.preference . The package defines classes to implement application preferences UI.
To see some more examples check Android’s Data Storage post on developers site.
Источник
How to Code a Settings Screen in an Android App
The material design team at Google gives a clear definition of what settings in your Android app should do:
App settings let users indicate preferences for how an app should behave.
Google also states that your users should navigate to the app settings either from the side navigation or toolbar menu—with an item labeled Settings.
Including settings in your app gives your users the power to control some of the functionality of your app. This makes your users happy instead of angry—because they are now in control of how the app behaves.
It’s highly recommended to give access to app settings. This will provide a better user experience for your users, which leads to a better review on the Google Play store, which then eventually gives rise to a higher number of app downloads (which boost revenue).
I assume you must have interacted with an app’s settings on your device, for example by selecting a default ringtone, or by controlling your privacy on the app. Almost all of the most popular apps you’ve downloaded or will download on the Google Play store include a settings screen for you to control the behaviour of the application.
An example of a popular app that has a settings screen is the Chrome Android app from Google. In this app’s settings screen, users can choose the default search engine, change the notification behaviour, control user privacy, etc. You can see this yourself by downloading the Chrome app from the Google Play store (if you don’t already have it on your device). The following screenshot is from the Chrome app, displaying the app’s settings screen.
In this post, you’ll learn how to create an app settings screen from scratch and also how to read the values the user has selected from the app settings. For an additional bonus, you’ll also learn how to use the Android Studio templates feature to quickly bootstrap your project with a settings screen.
A sample project (in Kotlin) for this tutorial can be found on our GitHub repo so you can easily follow along.
Prerequisites
To be able to follow this tutorial, you’ll need:
- A basic understanding of some Android APIs (such as SharedPreferences )
- Android Studio 3.0 or higher
- Kotlin plugin 1.1.51 or higher
1. Create an Android Studio Project
Fire up Android Studio and create a new project (you can name it SettingsScreenDemo ) with an empty activity called SettingsActivity . Make sure to also check the Include Kotlin support check box.
2. Creating a PreferenceFragment
To support API Level 11 (Honeycomb) and above, we can use the PreferenceFragment . This class is simply a Fragment that shows a hierarchy of Preference objects as lists.
In the code above, we created a nested class SettingsFragment inside SettingsActivity (because the SetttingsFragment class is so small). Note that our class SettingsFragment extends the PreferenceFragment superclass and has a method addPrerenceFromResource inside onCreate() . In this method, we gave it a resource ID R.xml.preference of the preference XML to launch—when the Fragment is loaded. Finally, we host the Fragment to the activity by simply using the FragmentTransaction to add it to the UI—inside onCreate() of SettingsActivity .
3. Creating Our Preferences
Create an XML file and name it preferences.xml. Save this file inside the res/xml directory in your app project. Note that you can give this file any name, but it’s highly recommended to stick with the conventional name «preferences». Also, you typically should have only one such file in an app project.
The root node for our preferences.xml file should be a
Other attributes you can add to a CheckBoxPreference are:
- android:summaryOff : sets the summary for the Preference in a preference screen when it’s unchecked.
- android:summaryOn : sets the summary for the Preference in a preference screen when it’s checked.
- android:disableDependentsState : The state (true for on, or false for off) that causes dependents to be disabled. May be a boolean value, such as «true» or «false».
Switch Preference
SwitchPreference performs similar functionality to the CheckBoxPreference . It provides a two-state («on» or «off») toggleable option. This uses a Switch widget that allows the user to slide left («off») and right («on»). This Preference also includes the attributes described for the CheckBoxPreference above. In addition, it has the following attributes:
- android:switchTextOff : sets the text used on the switch itself when in the «off» state.
- android:switchTextOn : sets the text used on the switch itself when in the «on» state.
EditText Preference
This Preference , when clicked, shows a dialog for the user to enter an input text. It uses the EditText widget—including all the attributes of that widget that you’re already familiar with.
Note that the value stored in the SharedPreferences is a string.
List Preference
This kind of Preference will display a list of entries in a dialog when tapped. Here, you can specify a pair of string-array resources in your preference XML. This string-array resource simply contains a collection of strings. This resource is located at res/values/arrays.xml .
Here is our sample ListPreference using this resource.
We set the entries and entry values using the android:entries and android:entryValues attributes respectively.
- android:entries : the human-readable array to present as a list.
- android:entryValues : the array to find the value to save for a preference when an entry from entries is selected.
For example, if we use the number of minutes in each duration as the entry values, when the user picks a time duration (e.g. 30 minutes), the corresponding integer value will be stored in SharedPreferences (e.g. 30).
MultiSelect List Preference
This one is similar to ListPreference but instead of having radio buttons, we have check boxes. In other words, the user can select multiple items in the dialog. Note that the result is stored in a “string set” in the SharedPreferences . This can be retrieved using getStringSet() .
Ringtone Preference
When a RingtonePreference is tapped, a dialog is shown containing the list of available ringtones on the device or emulator.
- android:showDefault : whether the Default ringtone option will be shown.
- android:showSilent : whether a Silent option will be shown in the list. The user can select this option if they don’t want to play any ringtone.
Note that the value stored in the SharedPreferences for this preference is a special string. This special string is a URI which points to a ContentProvider .
4. Creating Setting Groups
It becomes a problem when you have a long list of preferences or settings, because users may have some trouble scanning or understanding them. To solve this problem, we can group our preferences. Take a look at the screenshot of the Chrome app I showed you in the beginning again—notice it grouped the preferences into two categories: Basics and Advanced. This makes it easier for the user to understand the preferences and to not make the list seem too overwhelming.
Let’s now look at how simple it is to perform this task.
We simply surround the preferences we want to group in a
Here, we added a element inside the
6. Binding the Preference Summary to the Value Selected
Let’s now see how to update the preference summary with the value selected by the user.
In this class, we created a helper method called bindPreferenceSummaryToValue() , which is inside our companion object, to update the preference summary text with the value the user has selected. We passed it a Preference object as an argument. The findPreference() will return a Preference using the Preference ‘s key.
We have a variable sBindPreferenceSummaryToValueListener that is an instance of Preference.OnPreferenceChangeListener . This is simply a preference change listener that will help us update the preference summary to the value the user has selected. We check for special cases, like when the selected preference is a RingtonePreference or a ListPreference . For those preference types, we do some special handling to get the summary string. If the preference is neither (like an EditTextPreference ), we just set the summary to the preference’s string value.
Inside the bindPreferenceSummaryToValue() , we set the preference change listener by calling onPreferenceChangeListener (in Java, it’s setOnPreferenceChangeListener instead) on the Preference object.
Now run the project again to see how it all works!
7. Retrieving Preference Values
To start getting preference values for the settings screen, we call getDefaultSharedPreference() which is inside the PreferenceManager class—passing it a Context object of the preferences whose values are wanted. Note that we get the values from the default SharedPreferences for our application.
You call the corresponding getter method for the type we want to retrieve the value from in SharedPreferences . You pass it the key as the first argument, and the default value is the second argument.
8. Bonus: Using Android Studio Templates
Now that you have learnt about the APIs involved to create a settings screen from scratch in Android, I’ll show you a shortcut that will make it quicker next time. You can choose to use a template instead of coding a settings screen from scratch.
Android Studio provides code templates that follow the Android design and development best practices. These existing code templates (available in Java and Kotlin) can help you quickly kick-start your project. One such template can be used to create a settings screen.
To use this handy feature for a new project, first fire up Android Studio.
Enter the application name and click the Next button. You can leave the defaults as they are in the Target Android Devices dialog.
Click the Next button again.
In the Add an Activity to Mobile dialog, scroll down and select Settings Activity. Click the Next button after that.
In the last dialog, you can rename the Activity name, layout name or title if you want. Finally, click the Finish button to accept all configurations.
Android Studio has now helped us to create a project with a settings activity. Really cool! You are strongly advised to explore the code generated.
You can use templates for an already existing Android Studio project too. Simply go to File > New > Activity > Settings Activity.
Note that the templates that come included with Android Studio are good for simple layouts and making basic apps, but if you want to really kick-start your app, you might consider some of the app templates available from Envato Market.
They’re a huge time saver for experienced developers, helping them to cut through the slog of creating an app from scratch and focus their talents instead on the unique and customised parts of creating a new app
Conclusion
In this tutorial, you learned how to create app settings in Android from scratch. We also explored how to easily and quickly use the Android Studio templates to create app settings.
I highly recommend checking out the official material design guidelines for settings to learn more about how to properly design and use settings in Android. Also, check out the official API guide to learn more about other APIs for creating a settings activity.
To learn more about coding for Android, check out some of our other courses and tutorials here on Envato Tuts+!
Источник