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

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

Интервал:

Закладка:

Сделать

Finding Yourself

The obvious thing to do with a location service is to figure out where you are right now.

To do that, you need to get a LocationManager— call getSystemService(LOCATION_SERVICE)from your activity or service and cast it to be a LocationManager.

The next step to find out where you are is to get the name of the LocationProvideryou want to use. Here, you have two main options:

• Ask the user to pick a provider.

• Find the best-match provider based on a set of criteria.

If you want the user to pick a provider, calling getProviders()on the LocationManagerwill give you a Listof providers, which you can then present to the user for selection.

Or, you can create and populate a Criteriaobject, stating the particulars of what you want out of a LocationProvider, such as the following:

setAltitudeRequired()to indicate if you need the current altitude or not

setAccuracy()to set a minimum level of accuracy, in meters, for the position

setCostAllowed()to control if the provider must be free or not (i.e., if it can incur a cost on behalf of the device user)

Given a filled-in Criteriaobject, call getBestProvider()on your LocationManager, and Android will sift through the criteria and give you the best answer. Note that not all of your criteria may be met — all but the monetary-cost criterion might be relaxed if nothing matches.

You are also welcome to hard-wire in a LocationProvidername (e.g., gps), perhaps just for testing purposes.

Once you know the name of the LocationProvider, you can call getLastKnownPosition()to find out where you were recently. Note, however, that “recently” might be fairly out-of-date (e.g., if the phone was turned off) or even null if there has been no location recorded for that provider yet. On the other hand, getLastKnownPosition()incurs no monetary or power cost, since the provider does not need to be activated to get the value.

These methods return a Locationobject, which can give you the latitude and longitude of the device in degrees as a Java double. If the particular location provider offers other data, you can get at that as well:

• For altitude, hasAltitude()will tell you if there is an altitude value, and getAltitude()will return the altitude in meters.

• For bearing (i.e., compass-style direction), hasBearing()will tell you if there is a bearing available, and getBearing()will return it as degrees east of true north.

• For speed, hasSpeed()will tell you if the speed is known, and getSpeed()will return the speed in meters per second.

A more likely approach to getting the Locationfrom a LocationProvider, though, is to register for updates, as described in the next section.

On the Move

Not all location providers are necessarily immediately responsive. GPS, for example, requires activating a radio and getting a fix from the satellites before you get a location. That is why Android does not offer a getMeMyCurrentLocationNow()method. Combine that with the fact that your users may well want their movements to be reflected in your application, and you are probably best off registering for location updates and using that as your means of getting the current location.

The Weatherand WeatherPlussample applications (available in the Source Code area at http://apress.com) show how to register for updates — call requestLocationUpdates()on your LocationManagerinstance. This takes four parameters:

1. The name of the location provider you wish to use

2. How long, in milliseconds, must have elapsed before we might get a location update

3. How far, in meters, the device must have moved before we might get a location update

4. A LocationListenerthat will be notified of key location-related events, as shown in the following code:

LocationListener onLocationChange = new LocationListener() {

publicvoid onLocationChanged(Location location) {

updateForecast(location);

}

publicvoid onProviderDisabled(String provider) {

// required for interface, not used

}

publicvoid onProviderEnabled(String provider) {

// required for interface, not used

}

publicvoid onStatusChanged(String provider, int status,

Bundle extras) {

// required for interface, not used

}

};

Here, all we do is call updateForecast()with the Locationsupplied to the onLocationChanged()callback method. The updateForecast()implementation, as shown in Chapter 30, builds a Web page with the current forecast for the location and sends a broadcast so the activity knows an update is available.

When you no longer need the updates, call removeUpdates()with the LocationListeneryou registered.

Are We There Yet? Are We There Yet? Are We There Yet?

Sometimes you want to know not where you are now, or even when you move, but when you get to where you’re going. This could be an end destination, or it could be getting to the next step on a set of directions so you can give the user the next turn.

To accomplish this, LocationManageroffers addProximityAlert(). This registers a PendingIntent, which will be fired off when the device gets within a certain distance of a certain location. The addProximityAlert()method takes the following as parameters:

• The latitude and longitude of the position that you are interested in.

• A radius, specifying how close you should be to that position for the Intent to be raised.

• A duration for the registration, in milliseconds — after this period, the registration automatically lapses. A value of -1 means the registration lasts until you manually remove it via removeProximityAlert().

• The PendingIntentto be raised when the device is within the “target zone” expressed by the position and radius.

Note that it is not guaranteed that you will actually receive an Intent if there is an interruption in location services or if the device is not in the target zone during the period of time the proximity alert is active. For example, if the position is off by a bit and the radius is a little too tight, the device might only skirt the edge of the target zone, or go by so quickly that the device’s location isn’t sampled while in the target zone.

It is up to you to arrange for an activity or intent receiver to respond to the Intentyou register with the proximity alert. What you then do when the Intentarrives is up to you: set up a notification (e.g., vibrate the device), log the information to a content provider, post a message to a Web site, etc. Note that you will receive the Intentwhenever the position is sampled and you are within the target zone — not just upon entering the zone. Hence, you will get the Intentseveral times, perhaps quite a few times depending on the size of the target zone and the speed of the device’s movement.

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

Интервал:

Закладка:

Сделать

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

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


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

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

x