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:name=".SekritApp"

android:label="Top Sekrit"

android:permission="vnd.tlagency.sekrits.SEE SEKRITS">

android:name="android.intent.category.LAUNCHER" />

Only applications that have requested your indicated permission will be able to access the secured component. In this case, “access” means the following:

• Activities cannot be started without the permission.

• Services cannot be started, stopped, or bound to an activity without the permission.

• Intent receivers ignore messages sent via sendBroadcast()unless the sender has the permission.

Content providers offer two distinct attributes: readPermissionand writePermission:

android:name=".SekritProvider"

android:authorities="vnd.tla.sekrits.SekritProvider"

android:readPermission="vnd.tla.sekrits.SEE SEKRITS"

android:writePermission="vnd.tla.sekrits.MOD SEKRITS" />

In this case, readPermissioncontrols access to querying the content provider, while writePermissioncontrols access to insert, update, or delete data in the content provider.

Enforcing Permissions Elsewhere

In your code, you have two additional ways to enforce permissions.

Your services can check permissions on a per-call basis via checkCallingPermission(). This returns PERMISSION GRANTEDor PERMISSION DENIED, depending on whether the caller has the permission you specified. For example, if your service implements separate read and write methods, you could get the effect of readPermissionand writePermissionin code by checking those methods for the permissions you need from Java.

Also, you can include a permission when you call sendBroadcast(). This means that eligible receivers must hold that permission; those without the permission are ineligible to receive it. For example, the Android subsystem presumably includes the RECEIVE SMSpermission when it broadcasts that an SMS message has arrived — this will restrict the receivers of that intent to be only those authorized to receive SMS messages.

May I See Your Documents?

There is no automatic discovery of permissions at compile time; all permission failures occur at runtime. Hence, it is important that you document the permissions required for your public APIs, including content providers, services, and activities intended for launching from other activities. Otherwise, the programmers attempting to interface with your application will have to find out the permission rules by trial and error.

Furthermore, you should expect that users of your application will be prompted to confirm any permissions your application says it needs. Hence, you need to document for your users what they should expect, lest they get confused by the question posed by the phone and elect to not install or use your application.

CHAPTER 30

Creating a Service

As noted previously, Android services are for long-running processes that may need to keep running even when decoupled from any activity. Examples include playing music even if the “player” activity gets garbage-collected, polling the Internet for RSS/Atom feed updates, and maintaining an online chat connection even if the chat client loses focus due to an incoming phone call.

Services are created when manually started (via an API call) or when some activity tries connecting to the service via inter-process communication (IPC). Services will live until no longer needed and if RAM needs to be reclaimed. Running for a long time isn’t without its costs, though, so services need to be careful not to use too much CPU or keep radios active much of the time, or else the service causes the device’s battery to get used up too quickly.

This chapter covers how you can create your own services; the next chapter covers how you can use such services from your activities or other contexts. Both chapters will analyze the Service/WeatherPlussample application, with this chapter focusing mostly on the WeatherPlusServiceimplementation. WeatherPlusServiceextends the weather-fetching logic of the original Internet/Weathersample, by bundling it in a service that monitors changes in location, so the weather is updated as the emulator is “moved”.

Service with Class

Creating a service implementation shares many characteristics with building an activity. You inherit from an Android-supplied base class, override some lifecycle methods, and hook the service into the system via the manifest.

The first step in creating a service is to extend the Serviceclass, in our case with our own WeatherPlusServicesubclass.

Just as activities have onCreate(), onResume(), onPause()and kin, Serviceimplementations can override three different lifecycle methods:

1. onCreate(), which, as with activities, is called when the service process is created

2. onStart(), which is called when a service is manually started by some other process, versus being implicitly started as the result of an IPC request (discussed more in Chapter 31)

3. onDestroy(), which is called as the service is being shut down.

Common startup and shutdown logic should go in onCreate()and onDestroy(); onStart()is mostly if your service needs data passed into it from the starting process and you don’t wish to use IPC.

For example, here is the onCreate()method for WeatherPlusService:

@Override

publicvoid onCreate() {

super. onCreate();

client = new DefaultHttpClient();

format = getString(R.string.url);

myLocationManager =

(LocationManager) getSystemService(Context.LOCATION_SERVICE);

myLocationManager. requestLocationUpdates("gps", 10000,

10000.0f, onLocationChange);

}

First, we chain upward to the superclass, so Android can do any setup work it needs to have done. Then we initialize our HttpClientand format string as we did in the Weather demo. We then get the LocationManagerinstance for our application and request to get updates as our location changes, via the gps LocationProvider, which will be discussed in Chapter 33.

The onDestroy()method is much simpler:

@Override

publicvoid onDestroy() {

super. onDestroy();

myLocationManager. removeUpdates(onLocationChange);

}

Here, we just shut down the location-monitoring logic, in addition to chaining upward to the superclass for any Android internal bookkeeping that might be needed.

In addition to those lifecycle methods, though, your service also needs to implement onBind(). This method returns an IBinder, which is the linchpin behind the IPC mechanism. If you’re creating a service class while reading this chapter, just have this method return null for now, and we’ll fill in the full implementation in the next section.

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

Интервал:

Закладка:

Сделать

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

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


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

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

x