Mark Murphy - Beginning Android

Здесь есть возможность читать онлайн «Mark Murphy - Beginning Android» весь текст электронной книги совершенно бесплатно (целиком полную версию без сокращений). В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Город: New York, Год выпуска: 2009, ISBN: 2009, Издательство: Apress, Жанр: Программирование, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.

Beginning Android: краткое содержание, описание и аннотация

Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «Beginning Android»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.

Master Android from first principles and begin the journey toward your own successful Android applications!
Dear Reader,
First, welcome to the world of Android! We’re entering a new era of mobile application development, one marked by open platforms and open source, to take ‘walled gardens’ and make them green houses for any and all to participate in. Android is relatively easy for developers, and I believe that this innovation will help generate a large ecosystem of developers and consumers within a very short time. This means that budding developers such as yourself will have many opportunities to design and build your own applications and you’ll have a huge and hungry customer base.
Second, welcome to the book! Its purpose is to start you on your way with building Android applications, and to help you master the learning curve. Android is already a rich framework, comparable in many ways to the richness Android of desktop Java environments. This means that there is a lot of cool stuff for you to pick up along your journey in order to create the slickest, most useful apps Android you can imagine.
The source code for the code samples in this book is all available from the Apress site, so you can stay as hands-on and practical as you like while I introduce you to the core of Android, and invite you to experiment with the various classes and APIs we’ll be looking at. By the time you’ve finished this book, you’ll be creating your own Android applications and asking yourself what your next great application will be…!
Enjoy! Mark Murphy

Beginning Android — читать онлайн бесплатно полную книгу (весь текст) целиком

Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «Beginning Android», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

That instance state is provided to you again in:

onCreate()

onRestoreInstanceState()

It is your choice when you wish to re-apply the state data to your activity — either callback is a reasonable option.

PART 3

Data Stores, Network Services, and APIs

CHAPTER 17

Using Preferences

Android has many different ways for you to store data for long-term use by your activity. The simplest to use is the preferences system.

Android allows activities and applications to keep preferences, in the form of key/value pairs (akin to a Map), that will hang around between invocations of an activity. As the name suggests, the primary purpose is for you to store user-specified configuration details, such as the last feed the user looked at in your feed reader, or what sort order to use by default on a list, or whatever. Of course, you can store in the preferences whatever you like, so long as it is keyed by a Stringand has a primitive value (boolean, String, etc.).

Preferences can either be for a single activity or shared among all activities in an application. Eventually preferences might be shareable across applications, but that is not supported as of the time of this writing.

Getting What You Want

To get access to the preferences, you have three APIs to choose from:

getPreferences()from within your Activity, to access activity-specific preferences

getSharedPreferences()from within your Activity(or other application Context), to access application-level preferences

getDefaultSharedPreferences(), on PreferencesManager, to get the shared preferences that work in concert with Android’s overall preference framework

The first two take a security-mode parameter — for now, pass in 0. The getSharedPreferences()method also takes a name of a set of preferences — getPreferences()effectively calls getSharedPreferences()with the activity’s class name as the preference set name. The getDefaultSharedPreferences()method takes the Contextfor the preferences (e.g., your Activity).

All of those methods return an instance of SharedPreferences, which offers a series of getters to access named preferences, returning a suitably typed result (e.g., getBoolean()to return a Booleanpreference). The getters also take a default value, which is returned if there is no preference set under the specified key.

Stating Your Preference

Given the appropriate SharedPreferencesobject, you can use edit() to get an “editor” for the preferences. This object has a group of setters that mirror the getters on the parent SharedPreferencesobject. It also has the following:

remove()to get rid of a single named preference

clear()to get rid of all preferences

commit()to persist your changes made via the editor

The last one is important — if you modify preferences via the editor and fail to commit()the changes, those changes will evaporate once the editor goes out of scope.

Conversely, since the preferences object supports live changes, if one part of your application (say, an activity) modifies shared preferences, another part of your application (say, a service) will have access to the changed value immediately.

And Now, a Word from Our Framework

Beginning with the 0.9 SDK, Android has a framework for managing preferences. This framework does not change anything mentioned previously. Instead, the framework is more for presenting consistent preference-setting options for users so different applications do not have to reinvent the wheel.

The linchpin to the preferences framework is yet another XML data structure. You can describe your application’s preferences in an XML file stored in your project’s res/xml/directory. Given that, Android can present a pleasant UI for manipulating those preferences, which are then stored in the SharedPreferencesyou get back from getDefaultSharedPreferences().

The following is the preference XML for the Prefs/Simplepreferences sample project available in the Source Code section at http://apress.com:

xmlns:android="http://schemas.android.com/apk/res/android">

android:key="@string/checkbox"

android:title="Checkbox Preference"

android:summary="Check it on, check it off" />

android:key="@string/ringtone"

android:title="Ringtone Preference"

android:showDefault="true"

android:showSilent="true"

android:summary="Pick a tone, any tone" />

The root of the preference XML is a PreferenceScreenelement. (I will explain why it is named that later in this chapter; for now, take it on faith that it is a sensible name.) One of the things you can have inside a PreferenceScreenelement, not surprisingly, is preference definitions — subclasses of Preference, such as CheckBoxPreferenceor RingtonePreference, as shown in the preceding code. As one might expect, these allow you to check a checkbox and choose a ringtone, respectively. In the case of RingtonePreference, you have the option of allowing users to choose the system-default ringtone or to choose “silence” as a ringtone.

Letting Users Have Their Say

Given that you have set up the preference XML, you can use a nearly built-in activity for allowing your users to set their preferences. The activity is “nearly built-in” because you merely need to subclass it and point it to your preference XML, plus hook the activity into the rest of your application.

So, for example, here is the EditPreferencesactivity of the Prefs/Simpleproject available on the Apress Web site:

packagecom.commonsware.android.prefs;

importandroid.app.Activity;

importandroid.os.Bundle;

importandroid.preference.PreferenceActivity;

public classEditPreferences extendsPreferenceActivity {

@Override

publicvoid onCreate(Bundle savedInstanceState) {

super. onCreate(savedInstanceState);

addPreferencesFromResource(R.xml.preferences);

}

}

As you can see, there is not much to see. All you need to do is call addPreferencesFromResource()and specify the XML resource containing your preferences. You will also need to add this as an activity to your AndroidManifest.xmlfile:

package="com.commonsware.android.prefs">

android:name=".SimplePrefsDemo"

android:label="@string/app_name">

android:name=".EditPreferences"

android:label="@string/app_name">

And you will need to arrange to invoke the activity, such as from a menu option, here pulled from SimplePrefsDemoat http://apress.com:

@Override

publicboolean onCreateOptionsMenu(Menu menu) {

Читать дальше
Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Похожие книги на «Beginning Android»

Представляем Вашему вниманию похожие книги на «Beginning Android» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.


Отзывы о книге «Beginning Android»

Обсуждение, отзывы о книге «Beginning Android» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.

x