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

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

Интервал:

Закладка:

Сделать

But first, we need to make a small change to our manifest:

package="com.commonsware.android.rotation.three"

android:versionCode="1"

android:versionName="1.0.0">

android:label="@string/app_name"

android:configChanges="keyboardHidden|orientation">

Here, we state that we will handle keyboardHiddenand orientationconfiguration changes ourselves. This covers us for any cause of the “rotation” — whether it is a sliding keyboard or a physical rotation. Note that this is set on the activity, not the application — if you have several activities, you will need to decide for each which of the tactics outlined in this chapter you wish to use.

The Java code for this project follows:

public classRotationThreeDemo extendsActivity {

static finalint PICK_REQUEST = 1337;

Button viewButton = null;

Uri contact = null;

@Override

publicvoid onCreate(Bundle savedInstanceState) {

super. onCreate(savedInstanceState);

setupViews();

}

@Override

protectedvoid onActivityResult(int requestCode, int resultCode,

Intent data) {

if(requestCode==PICK_REQUEST) {

if(resultCode==RESULT_OK) {

contact = data. getData();

viewButton. setEnabled( true);

}

}

}

publicvoid onConfigurationChanged(Configuration newConfig) {

super. onConfigurationChanged(newConfig);

setupViews();

}

privatevoid setupViews() {

setContentView(R.layout.main);

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

btn. setOnClickListener( newView. OnClickListener() {

publicvoid onClick(View view) {

Intent i = new Intent(Intent.ACTION_PICK,

Uri. parse("content://contacts/people"));

startActivityForResult(i, PICK_REQUEST);

}

});

viewButton = (Button) findViewById(R.id.view);

viewButton. setOnClickListener( newView. OnClickListener() {

publicvoid onClick(View view) {

startActivity( new Intent(Intent.ACTION_VIEW, contact));

}

});

viewButton. setEnabled(contact!= null);

}

}

The onCreate()implementation delegates most of its logic to a setupViews()method, which loads the layout and sets up the buttons. The reason this logic was broken out into its own method is because it is also called from onConfigurationChanged().

Forcing the Issue

In the previous three sections, we covered ways to deal with rotational events. There is, of course, a radical alternative: tell Android not to rotate your activity at all. If the activity does not rotate, you do not have to worry about writing code to deal with rotations.

To block Android from rotating your activity, all you need to do is add android:screenOrientation="portrait"(or "landscape", as you prefer) to your AndroidManifest.xml file, as shown (from the Rotation/RotationFoursample project):

package="com.commonsware.android.rotation.four"

android:versionCode="1"

android:versionName="1.0.0">

android:screenOrientation="portrait"

android:label="@string/app_name">

Since this is applied on a per-activity basis, you will need to decide which of your activities may need this turned on.

At this point, your activity is locked into whatever orientation you specified, regardless of what you do. The following screen shots show the same activity as in the previous three sections, but using the previous manifest and with the emulator set for both portrait and landscape orientation. Note that the UI does not move a bit, but remains in portrait mode as can be seen in Figures 26-3 and 26-4.

Figure 263 The RotationFour application in portrait mode Figure 264 The - фото 82

Figure 26-3. The RotationFour application, in portrait mode

Figure 264 The RotationFour application in landscape mode Making Sense of - фото 83

Figure 26-4. The RotationFour application, in landscape mode

Making Sense of it All

All of these scenarios assume that you rotate the screen by opening up the keyboard on the device (or pressing -in the emulator). Certainly, this is the norm for Android applications.

However, we haven’t covered the iPhone Scenario.

You may have seen one (or several) commercials for the iPhone, showing how the screen rotates just by turning the device. By default, you do not get this behavior with the T-Mobile G1 — instead, the screen rotates based on whether the keyboard is open or closed.

However, it is very easy for you to change this behavior, so your screen will rotate based on the position of the phone: just add android:screenOrientation="sensor"to your AndroidManifest.xmlfile (as seen in the Rotation/RotationFivesample project):

package="com.commonsware.android.rotation.five"

android:versionCode="1"

android:versionName="1.0.0">

android:screenOrientation="sensor"

android:label="@string/app_name">

The “sensor”, in this case, tells Android you want the accelerometers to control the screen orientation, so the physical shift in the device orientation controls the screen orientation.

At least on the G1, this appears to only work when going from the traditional upright portrait position to the traditional landscape position — rotating 90 degrees counter-clockwise. Rotating the device 90 degrees clockwise results in no change in the screen.

Also note that this setting disables having the keyboard trigger a rotation event. Leaving the device in the portrait position, if you slide out the keyboard, in a “normal” Android activity, the screen will rotate; in a android:screenOrientation="sensor"activity, the screen will not rotate.

PART 5

Content Providers and Services

CHAPTER 27

Using a Content Provider

Any Uriin Android that begins with the content://schemerepresents a resource served up by a content provider. Content providers offer data encapsulation using Uriinstances as handles — you neither know nor care where the data represented by the Uricomes from, so long as it is available to you when needed. The data could be stored in a SQLite database, or in flat files, or retrieved off a device, or be stored on some far-off server accessed over the Internet.

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

Интервал:

Закладка:

Сделать

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

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


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

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

x