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

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

Интервал:

Закладка:

Сделать

Seeing Pestering in Action

Let us now take a peek at the Notifications/Notify1sample project (available in the Source Code section at http://apress.com), in particular the NotifyDemoclass:

public classNotifyDemo extendsActivity {

private static finalint NOTIFY_ME_ID = 1337;

privateTimer timer = new Timer();

privateint count = 0;

@Override

publicvoid onCreate(Bundle savedInstanceState) {

super. onCreate(savedInstanceState);

setContentView(R.layout.main);

Button btn = (Button) findViewById(R.id.notify);

btn. setOnClickListener( newView. OnClickListener() {

publicvoid onClick(View view) {

TimerTask task = new TimerTask() {

publicvoid run() {

notifyMe();

}

};

timer. schedule(task, 5000);

}

});

btn = (Button) findViewById(R.id.cancel);

btn. setOnClickListener( newView. OnClickListener() {

publicvoid onClick(View view) {

NotificationManager mgr =

(NotificationManager) getSystemService(NOTIFICATION_SERVICE);

mgr. cancel(NOTIFY_ME_ID);

}

});

}

privatevoid notifyMe() {

finalNotificationManager mgr =

(NotificationManager) getSystemService(NOTIFICATION_SERVICE);

Notification note = new Notification(R.drawable.red_ball,

"Status message!", System. currentTimeMillis());

PendingIntent i = PendingIntent. getActivity( this, 0,

new Intent( this, NotifyMessage. class), 0);

note. setLatestEventInfo( this, "Notification Title",

"This is the notification message", i);

note.number = ++count;

mgr. notify(NOTIFY_ME_ID, note);

This activity sports two large buttons, one to kick off a notification after a five-second delay, and one to cancel that notification (if it is active). See Figure 32-1.

Figure 321 The NotifyDemo activity main view Creating the notification in - фото 86

Figure 32-1. The NotifyDemo activity main view

Creating the notification, in notifyMe(), is accomplished in five steps:

1. Get access to the NotificationManagerinstance.

2. Create a Notificationobject with our icon (red ball), a message to flash on the status bar as the notification is raised, and the time associated with this event.

3. Create a PendingIntentthat will trigger the display of another activity ( NotifyMessage).

4. Use setLatestEventInfo()to specify that, when the notification is clicked on, we are to display a certain title and message, and if that is clicked on, we launch the PendingIntent.

5. Tell the NotificationManagerto display the notification.

Hence, if we click the top button, after five seconds our red ball icon will appear in the status bar. Our status message will also appear briefly, as shown in Figure 32-2.

Figure 322 Our notification as it appears on the status bar with our status - фото 87

Figure 32-2. Our notification as it appears on the status bar, with our status message

If you click on the red ball, a drawer will appear beneath the status bar. Drag that drawer all the way to the bottom of the screen to show the outstanding notifications, including our own, as shown in Figure 32-3.

Figure 323 The notifications drawer fully expanded with our notification - фото 88

Figure 32-3. The notifications drawer, fully expanded, with our notification

If you click on the notification entry in the drawer, you’ll be taken to a trivial activity displaying a message — though in a real application this activity would do something useful based upon the event that occurred (e.g., take users to the newly arrived mail messages).

Clicking on the cancel button, or clicking on the Clear Notifications button in the drawer, will remove the red ball from the status bar.

PART 6

Other Android Capabilities

CHAPTER 33

Accessing Location-Based Services

A popular feature on current-era mobile devices is GPS capability, so the device can tell you where you are at any point in time. While the most popular use of GPS service is mapping and directions, there are other things you can do if you know your location. For example, you might set up a dynamic chat application where the people you can chat with are based on physical location, so you’re chatting with those you are nearest. Or you could automatically geotag posts to Twitter or similar services.

GPS is not the only way a mobile device can identify your location. Alternatives include the following:

• The European equivalent to GPS, called Galileo, which is still under development at the time of this writing

• Cell-tower triangulation, where your position is determined based on signal strength to nearby cell towers

• Proximity to public WiFi “hotspots” that have known geographic locations

Android devices may have one or more of these services available to them. You, as a developer, can ask the device for your location, plus details on what providers are available. There are even ways for you to simulate your location in the emulator, for use in testing your location-enabled applications.

Location Providers: They Know Where You’re Hiding

Android devices can have access to several different means of determining your location. Some will have better accuracy than others. Some may be free, while others may have a cost associated with them. Some may be able to tell you more than just your current position, such as your elevation over sea level, or your current speed.

Android, therefore, has abstracted all this out into a set of LocationProviderobjects. Your Android environment will have zero or more LocationProviderinstances, one for each distinct locating service that is available on the device. Providers know not only your location, but their own characteristics, in terms of accuracy, cost, etc.

You, as a developer, will use a LocationManager, which holds the LocationProviderset, to figure out which LocationProvideris right for your particular circumstance. You will also need the ACCESS_LOCATIONpermission in your application, or the various location APIs will fail due to a security violation. Depending on which location providers you wish to use, you may need other permissions as well, such as ACCESS_COARSE_LOCATIONor ACCESS_FINE_LOCATION.

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

Интервал:

Закладка:

Сделать

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

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


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

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

x