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

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

Интервал:

Закладка:

Сделать

Second, scripting languages without JIT will inevitably be slower than compiled Dalvik applications. Slower may mean users experience sluggishness. Slower definitely means more battery life is consumed for the same amount of work. So, building a whole Android application in BeanShell, simply because you feel it is easier to program in may cause your users to be unhappy.

Third, scripting languages that expose the whole Java API, like BeanShell, can pretty much do anything the underlying Android security model allows. So, if your application has the READ_CONTACTSpermission, expect any BeanShell scripts your application runs to have the same permission.

Last, but certainly not least, is that language interpreter JARs tend to be… portly. The BeanShell JAR used in this example is 200KB. That is not ridiculous, considering what it does, but it will make applications that use BeanShell that much bigger to download, take up that much more space on the device, etc.

…And Not a Drop to Drink

Not all Java code will work on Android and Dalvik. Specifically consider the following:

• If the Java code assumes it runs on Java SE, Java ME, or Java EE, it may be missing some APIs that those platforms provide that Android does not. For example, some charting libraries assume the existence of Swing or Abstract Window Toolkit (AWT) drawing primitives, which are generally unavailable on Android.

• The Java code might have a dependency on other Java code that, in turn, might have problems running on Android. For example, you might want to use a JAR that relies upon an earlier (or newer) version of the Apache HTTPComponents than the one that is bundled with Android.

• The Java code may use language capabilities beyond what the Dalvik engine is capable of using.

In all these cases, if you have only a compiled JAR to work with, you may not encounter problems at compile time, but rather when running the application. Hence, where possible it is best to use open-source code with Android so you can build the third-party code alongside your own and find out about difficulties sooner.

CHAPTER 22

Communicating via the Internet

The expectation is that most, if not all, Android devices will have built-in Internet access. That could be WiFi, cellular data services (EDGE, 3G, etc.), or possibly something else entirely. Regardless, most people — or at least those with a data plan or WiFi access — will be able to get to the Internet from their Android phone.

Not surprisingly, the Android platform gives developers a wide range of ways to make use of this Internet access. Some offer high-level access, such as the integrated WebKit browser component we saw in Chapter 13. If you want, you can drop all the way down to using raw sockets. Or, in between, you can leverage APIs — both on-device and from 3rd-party JARs — that give you access to specific protocols: HTTP, XMPP, SMTP, and so on.

The emphasis of this book is on the higher-level forms of access: the WebKit component and Internet-access APIs, as busy coders should be trying to reuse existing components versus rolling one’s own on-the-wire protocol wherever possible.

REST and Relaxation

Android does not have built-in SOAP or XML-RPC client APIs. However, it does have the Apache HttpComponents library baked in. You can either layer a SOAP/XML-RPC layer atop this library, or use it “straight” for accessing REST-style Web services. For the purposes of this book, “REST-style Web services” is defined as simple HTTP requests for ordinary URLs over the full range of HTTP verbs, with formatted payloads (XML, JSON, etc.) as responses.

More expansive tutorials, FAQs, and HOWTOs can be found at the HttpComponents Web site. [28] http://hc.apache.org/ Here, we’ll cover the basics, while checking the weather.

HTTP Operations via Apache HttpComponents

The HTTPClient component of HttpComponents handles all HTTP requests on your behalf. The first step to using HttpClient is, not surprisingly, to create an HttpClientobject. Since HttpClientis an interface, you will need to actually instantiate some implementation of that interface, such as DefaultHttpClient.

Those requests are bundled up into HttpRequest instances, with different HttpRequestimplementations for each different HTTP verb (e.g., HttpGetfor HTTP GETrequests). You create an HttpRequestimplementation instance, fill in the URL to retrieve and other configuration data (e.g., form values if you are doing an HTTP POSTvia HttpPost), then pass the method to the client to actually make the HTTP request via execute().

What happens at this point can be as simple or as complicated as you want. You can get an HttpResponseobject back, with response code (e.g., 200 for OK), HTTP headers, and the like. Or, you can use a flavor of execute()that takes a ResponseHandleras a parameter — the net result there being that execute()returns just the Stringrepresentation of the request body. In practice, this is not a recommended approach, because you really should be checking your HTTP response codes for errors. However, for trivial applications, like book examples, the ResponseHandlerapproach works just fine.

For example, let’s take a look at the Internet/Weathersample project. This implements an activity that retrieves weather data for your current location from the National Weather Service (Note: this probably only works in the US). That data is converted into an HTML page, which is poured into a WebKitwidget for display. Rebuilding this demo using a ListViewis left as an exercise for the reader. Also, since this sample is relatively long, we will only show relevant pieces of the Java code here in this chapter, though you can always download the full source from the CommonsWare Web site. [29] http://commonsware.com/Android/

To make this a bit more interesting, we use the Android location services to figure out where we are… sort of. The full details of how that works is described in Chapter 33.

In the onResume()method, we toggle on location updates, so we will be informed where we are now and when we move a significant distance (10km). When a location is available — either at the start or based on movement — we retrieve the National Weather Service data via our updateForecast()method:

privatevoid updateForecast(Location loc) {

String url = String. format(format, loc. getLatitude(), loc. getLongitude());

HttpGet getMethod = new HttpGet(url);

try{

ResponseHandler responseHandler = new BasicResponseHandler();

String responseBody = client. execute(getMethod, responseHandler);

buildForecasts(responseBody);

String page = generatePage();

browser. loadDataWithBaseURL( null, page, "text/html",

"UTF-8", null);

} catch(Throwable t) {

Toast. makeText( this, "Request failed: " + t. toString(), 4000). show();

}

}

The updateForecast()method takes a Locationas a parameter, obtained from the location update process. For now, all you need to know is that Location sports getLatitude()and getLongitude()methods that return the latitude and longitude of the device’s position, respectively.

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

Интервал:

Закладка:

Сделать

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

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


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

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