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

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

Интервал:

Закладка:

Сделать

android:orientation="vertical"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

>

style="?android:attr/progressBarStyleHorizontal"

android:layout_width="fill_parent"

android:layout_height="wrap_content" />

The ProgressBar, in addition to setting the width and height as normal, also employs the styleproperty, which I won’t cover in detail in this book. Suffice it to say, styleproperty indicates this ProgressBarshould be drawn as the traditional horizontal bar showing the amount of work that has been completed.

Here is the Java:

packagecom.commonsware.android.threads;

importandroid.app.Activity;

importandroid.os.Bundle;

importandroid.os.Handler;

importandroid.os.Message;

importandroid.widget.ProgressBar;

public classHandlerDemo extendsActivity {

ProgressBar bar;

Handler handler = new Handler() {

@Override

publicvoid handleMessage(Message msg) {

bar. incrementProgressBy(5);

}

};

boolean isRunning = false;

@Override

publicvoid onCreate(Bundle icicle) {

super. onCreate(icicle);

setContentView(R.layout.main);

bar = (ProgressBar) findViewById(R.id.progress);

}

publicvoid onStart() {

super. onStart();

bar. setProgress(0);

Thread background = new Thread( new Runnable() {

publicvoid run() {

try{

for(int i=0; i<20 && isRunning; i++) {

Thread. sleep(1000);

handler. sendMessage(handler. obtainMessage());

}

} catch(Throwable t) {

// just end the background thread

}

}

});

isRunning = true;

background. start();

}

publicvoid onStop() {

super. onStop();

isRunning = false;

}

}

As part of constructing the Activity, we create an instance of Handler, with our implementation of handleMessage(). Basically, for any message received, we update the ProgressBarby 5 points, then exit the message handler.

In onStart(), we set up a background thread. In a real system, this thread would do something meaningful. Here, we just sleep one second, post a Messageto the Handler, and repeat for a total of 20 passes. This, combined with the 5-point increase in the ProgressBarposition, will march the bar clear across the screen, as the default maximum value for ProgressBaris 100. You can adjust that maximum via setMax(), such as setting the maximum to be the number of database rows you are processing, and updating once per row.

Note that we then leave onStart(). This is crucial. The onStart()method is invoked on the activity UI thread, so it can update widgets and anything else that affects the UI, such as the title bar. However, that means we need to get out of onStart(), both to let the Handlerget its work done, and also so Android does not think our activity is stuck.

The resulting activity is simply a horizontal progress bar (see Figure 15-1).

Figure 151 The HandlerDemo sample application Runnables If you would - фото 55

Figure 15-1. The HandlerDemo sample application

Runnables

If you would rather not fuss with Messageobjects, you can also pass Runnableobjects to the Handler, which will run those Runnableobjects on the activity UI thread. Handler offers a set of post...()methods for passing Runnableobjects in for eventual processing.

Running in Place

Just as Handlersupports post()and postDelayed()to add Runnable objects to the event queue, you can use those same methods on View. This slightly simplifies your code, in that you can then skip the Handlerobject. However, you lose a bit of flexibility, and the Handlerhas been around longer in the Android toolkit and may be more tested.

Where, Oh Where Has My UI Thread Gone?

Sometimes, you may not know if you are currently executing on the UI thread of your application. For example, if you package some of your code in a JAR for others to reuse, you might not know whether your code is being executed on the UI thread or from a background thread.

To help combat this problem, Activityoffers runOnUiThread(). This works similar to the post()methods on Handlerand View, in that it queues up a Runnableto run on the UI thread, if you are not on the UI thread right now. If you already are on the UI thread, it invokes the Runnableimmediately. This gives you the best of both worlds: no delay if you are on the UI thread, yet safety in case you are not.

Now, the Caveats

Background threads, while eminently possible using the Android Handlersystem, are not all happiness and warm puppies. Background threads not only add complexity, but they have real-world costs in terms of available memory, CPU, and battery life.

To that end, there are a wide range of scenarios you need to account for with your background thread, including

• The possibility that users will interact with your activity’s UI while the background thread is chugging along. If the work that the background thread is doing is altered or invalidated by the user input, you will need to communicate this to the background thread. Android includes many classes in the java.util.concurrentpackage that will help you communicate safely with your background thread.

• The possibility that the activity will be killed off while background work is going on. For example, after starting your activity, the user might have a call come in, followed by a text message, then a need to look up a contact — all of which might be sufficient to kick your activity out of memory. Chapter 16 will cover the various events Android will take your activity through; hook the proper ones and be sure to shut down your background thread cleanly when you have the chance.

• The possibility that your user will get irritated if you chew up a lot of CPU time and battery life without giving any payback. Tactically, this means using ProgressBaror other means of letting the user know that something is happening. Strategically, this means you still need to be efficient at what you do — background threads are no panacea for sluggish or pointless code.

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

Интервал:

Закладка:

Сделать

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

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


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

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

x