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», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

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

Интервал:

Закладка:

Сделать

What’s Your Intent?

When Sir Tim Berners-Lee cooked up the Hypertext Transfer Protocol — HTTP — he set up a system of verbs plus addresses in the form of URLs. The address indicated a resource, such as a Web page, graphic, or server-side program. The verb indicated what should be done: GET to retrieve it, POST to send form data to it for processing, etc.

Intents are similar, in that they represent an action plus context. There are more actions and more components to the context with Android intents than there are with HTTP verbs and resources, but the concept is still the same.

Just as a Web browser knows how to process a verb + URL pair, Android knows how to find activities or other application logic that will handle a given intent.

Pieces of Intents

The two most important pieces of an intent are the action and what Android refers to as the “data”. These are almost exactly analogous to HTTP verbs and URLs — the action is the verb, and the “data” is a Uri, such as content://contacts/people/1representing a contact in the contacts database. Actions are constants, such as ACTION_VIEW(to bring up a viewer for the resource), ACTION_EDIT(to edit the resource), or ACTION_PICK(to choose an available item given aUri representing a collection, such as content://contacts/people).

If you wereto create an intent combining ACTION_VIEWwith a content Uriof content://contacts/people/1, and pass that intent to Android, Android would know to find and open an activity capable of viewing that resource.

There are other criteria you can place inside an intent (represented as an Intent object), besides the action and “data” Uri, such as:

• A category. Your “main” activity will be in the LAUNCHERcategory, indicating it should show up on the launcher menu. Other activities will probably be in the DEFAULTor ALTERNATIVEcategories.

• A MIME type, indicating the type of resource you want to operate on, if you don’t know a collection Uri.

• A component, which is to say, the class of the activity that is supposed to receive this intent. Using components this way obviates the need for the other properties of the intent. However, it does make the intent more fragile, as it assumes specific implementations.

• “Extras”, which is a Bundle of other information you want to pass along to the receiver with the intent, that the receiver might want to take advantage of. What pieces of information a given receiver can use is up to the receiver and (hopefully) is well-documented.

You will find rosters of the standard actions and categories in the Android SDK documentation for the Intent class.

Intent Routing

As previously noted, if you specify the target component in your intent, Android has no doubt where the intent is supposed to be routed to — it will launch the named activity. This might be OK if the target intent is in your application. It definitely is not recommended for sending intents to other applications. Component names, by and large, are considered private to the application and are subject to change. Content Uritemplates and MIME types are the preferred ways of identifying services you wish third-party code to supply.

If you do not specify the target component, then Android has to figure out what activities (or other intent receivers) are eligible to receive the intent. Note the use of the plural “activities”, as a broadly-written intent might well resolve to several activities. That is the… ummm… intent (pardon the pun), as you will see later in this chapter. This routing approach is referred to as implicit routing.

Basically, there are three rules, all of which must be true for a given activity to be eligible for a given intent:

1. The activity must support the specified action.

2. The activity must support the stated MIME type (if supplied).

3. The activity must support all of the categories named in the intent.

The upshot is that you want to make your intents specific enough to find the right receiver(s), and no more specific than that.

This will become clearer as we work through some examples later in this chapter.

Stating Your Intent(ions)

All Android components that wish to be notified via intents must declare intent filters, so Android knows which intents should go to that component. To do this, you need to add intent-filterelements to your AndroidManifest.xmlfile.

All of the example projects have intent filters defined, courtesy of the Android application-building script ( activityCreatoror the IDE equivalent). They look something like this:

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

Note the intent-filterelement under the activityelement. Here, we declare that this activity:

• is the main activity for this application

• is in the LAUNCHERcategory, meaning it gets an icon in the Android main menu

Because this activity is the main one for the application, Android knows this is the component it should launch when somebody chooses the application from the main menu.

You are welcome to have more than one action or more than one category in your intent filters. That indicates that the associated component (e.g., activity) handles multiple different sorts of intents.

More than likely, you will also want to have your secondary (non-MAIN) activities specify the MIME type of data they work on. Then, if an intent is targeted for that MIME type — either directly, or indirectly by the Uri referencing something of that type — Android will know that the component handles such data.

For example, you could have an activity declared like this:

This activity will get launched by an intent requesting to view a Urirepresenting a vnd.android.cursor.item/vnd.commonsware.tourpiece of content. That intent could come from another activity in the same application (e.g., the MAIN activity for this application) or from another activity in another Android application that happens to know a Urithat this activity handles.

Narrow Receivers

In the examples shown previously, the intent filters were set up on activities. Sometimes, tying intents to activities is not exactly what we want:

• Some system events might cause us to want to trigger something in a service rather than an activity.

• Some events might need to launch different activities in different circumstances, where the criteria are not solely based on the intent itself, but some other state (e.g., if we get intent X and the database has a Y, then launch activity M; if the database does not have a Y, then launch activity N).

For these cases, Android offers the intent receiver, defined as a class implementing the BroadcastReceiverinterface. Intent receivers are disposable objects designed to receive intents — particularly broadcast intents — and take action, typically involving launching other intents to trigger logic in an activity, service, or other component.

The BroadcastReceiverinterface has only one method: onReceive(). Intent receivers implement that method, where they do whatever it is they wish to do upon an incoming intent. To declare an intent receiver, add a receiver element to your AndroidManifest.xmlfile:

An intent receiver is only alive for as long as it takes to process onReceive()— as soon as that method returns, the receiver instance is subject to garbage collection and will not be reused. This means intent receivers are somewhat limited in what they can do, mostly to avoid anything that involves any sort of callback. For example, they cannot bind to a service, and they cannot open a dialog box.

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

Интервал:

Закладка:

Сделать

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

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


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

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

x