34
Android Development Tutorial - Gingerbread Lars Vogel Version 4.4 Copyright © 2009 - 2010 Lars Vogel 06.12.2010 Revision History Revision 0.1 04.07.2009 Lars Vogel Created Revision 0.2 - 4.4 07.07.2009 - 06.12.2010 Lars Vogel bug fixing and enhancements Development with Android Froyo and Eclipse This tutorial describes how to create Android applications with Eclipse. It is based on Eclipse 3.6, Java 1.6 and Android 2.3 (Gingerbread). Table of Contents 1. Android Development 1.1. Android Operation System 1.2. Important Android components 1.3. AndroidManifest.xml 1.4. R.java, Resources and Assets 1.5. Activities and Layouts 1.6. Activities and Lifecyle 1.7. Context 2. Installation 2.1. Android SDK 2.2. Eclipse 2.3. Configuration 2.4. Device 3. Error handling 4. Your first Android project

Android Development Tutorial

Embed Size (px)

Citation preview

Page 1: Android Development Tutorial

Android Development Tutorial - Gingerbread

Lars Vogel

Version 4.4

Copyright © 2009 - 2010 Lars Vogel

06.12.2010

Revision History

Revision 0.1 04.07.2009 Lars Vogel

Created

Revision 0.2 - 4.4 07.07.2009 - 06.12.2010 Lars Vogel

bug fixing and enhancements

Development with Android Froyo and Eclipse

This tutorial describes how to create Android applications with Eclipse. It is based on Eclipse 3.6, Java 1.6 and Android 2.3 (Gingerbread).

Table of Contents

1. Android Development1.1. Android Operation System1.2. Important Android components 1.3. AndroidManifest.xml 1.4. R.java, Resources and Assets1.5. Activities and Layouts 1.6. Activities and Lifecyle 1.7. Context

2. Installation2.1. Android SDK2.2. Eclipse2.3. Configuration2.4. Device

3. Error handling4. Your first Android project

4.1. Create Project4.2. Two faces of things4.3. Create attributes4.4. Add UI Elements4.5. Maintain UI properties4.6. Code your application4.7. Start Project4.8. Using the home menue

Page 2: Android Development Tutorial

5. Lists5.1. Overview5.2. Simple ListActivities5.3. ListActivities with own layout5.4. ListActivities with flexible layout

6. Menu, Preferences and Intents6.1. Project6.2. Add a menu6.3. Using preferences6.4. Run

7. ContentProvider7.1. Overview7.2. Create contacts on your emulator7.3. Example

8. ScrollView9. Services and Broadcast Receiver10. Important views

10.1. LogCat View10.2. File explorer

11. Shell11.1. Android Debugging Bridge - Shell11.2. Uninstall an application via adb11.3. Emulator Console via telnet

12. Deploy your application on a real device13. Thank you 14. Questions and Discussion15. Links and Literature

15.1. Source Code15.2. Android Resources15.3. vogella Resources

1. Android Development

1.1. Android Operation System

Android is an operating system based on Linux with a Java programming interface. It provides tools, e.g. a compiler, debugger and a device emulator as well as its own Java Virtual machine (Dalvik Virtual Machine - DVM). Android is created by the Open Handset Alliance which is lead by Google.

Android uses a special Java virtual machine (Dalvik). Dalvik uses special bytecode. Therefore you cannot run standard Java bytecode on Android. Android provides a tool "dx" which allows to convert Java Class files into "dex" (Dalvik Executable) files. Android applications are packed into an .apk (Android Package) file. To simplify development Google provides the Android Development Tools (ADT) for Eclipse . The ADT performs automatically the conversion from class to dex files and creates the apk during deployment.

Android supports 2-D and 3-D graphics using the OpenGL libraries and supports data storage in a SQLLite database.

Page 3: Android Development Tutorial

Every Android applications runs in its own process and it isolated from other running applications. Therefore on misbehaving application cannot harm other Android applications.

1.2. Important Android components

An Android application consists out of the following parts:

Activity - Represents the presentation layer of an Android application, e.g. a screen which the user sees. An Android application can have several activities and it can be switched between them during runtime of the application. The User interface of an Activities is build with widgets classes which inherent from "android.view.View". The layout of the views is managed by ViewGroups.

Services - perform background activities without providing an UI. They can notify the user via the notification framework in Android.

Content Provider - provides data to applications, via a content provider your application can share data with other applications. Android contains a SQLLite DB which can serve as data provider

Intents allow the application to request and / or provide functionality from other services or activities. An application can call directly a service or activity (explicit intent) or asked the Android system for registered services and applications for an intent (implicit intents). For example the application could ask via an intent for a contact application. Application register themself via an IntentFilter. Intents are a powerful concept as they allow to create loosely coupled applications.

Broadcast Receiver - receives system messages and implicit intents, can be used to react to changed conditions in the system. An application can register as a broadcast receiver for certain events and can be started if such an event occurs.

Other Android parts are Android widgets or Live Folders and Live Wallpapers . Live Folders display any source of data on the homescreen without launching the corresponding application.

1.3. AndroidManifest.xml

An Android application is described the file "AndroidManifest.xml". This files must declare all activities, services, broadcast receivers and content provider of the application. It must also contain the required permissions for the application. For example if the application requires network access it must be specified here. "AndroidManifest.xml" can be thought as the deployment descriptor for an Android application.

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="de.vogella.android.temperature" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".Convert" android:label="@string/app_name">

Page 4: Android Development Tutorial

<intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity>

</application> <uses-sdk android:minSdkVersion="9" />

</manifest>

The "package" attribute defines the base package for the following Java elements. "activity" defines an activity in this example pointing to the class "de.vogella.android.temperature.Convert". For this class an intent filter is registered which defines that this activity is started ion the application starts (action android:name="android.intent.action.MAIN"). The category definition (category android:name="android.intent.category.LAUNCHER" ) defimes that this application is added to the application directory on the Android device. The @ values refer to resource files which contain the actual values. This makes it easy to provide different resources, e.g. strings, colors, icons, for different devices and makes it easy to translate applications.

1.4. R.java, Resources and Assets

The directory "gen" in an Android project contains generated values. "R.java" is a generated class which contains references to resources of the "res" folder in the project. System resources are maintained in the "res" directory and can be values, menus, layouts, icons or pictures or animations. These resources can for example be text or icons. If you create a new resources the corresponding reference is automatically created in R.java. The references are static int values, the Android system provides methods to access the corresponding resource. For example to access a String with the reference id "R.string.yourString" use the method getString(R.string.yourString)); Please do not try to modify "R.java" manually. While "res" contains structured values which are known to the Android platform the directory "assets" can be used to store any kind of data. In Java you can access this data via the AssetsManager and the method getAssets().

1.5. Activities and Layouts

The user interface for Activities is defined via layouts. The layout defines the UI elements, their properties and their arragement. A layout can be defined via XML and via code at runtime. The XML way is usually preferred for a fixed layout while defining the layout via code is more flexible. You can also mix both approaches.

1.6. Activities and Lifecyle

The operating system controls the life cycle of your application. At any time the Android system may stop or destroy your application, e.g. because of an incoming call. The Android system defines a life cycle for an activities via pre-defined methods. The most important methods are:

Page 5: Android Development Tutorial

onSaveInstanceState() - called if the activity is stopped. Used to save data so that the activity can restore its states if re-started

onPause() - always called if the Activity ends, can be used to release ressource or save data

onResume() - called if the Activity is re-started, can be used to initiaze fields

1.7. Context

The class android.content.Context provides the connections to the Android system. Contexts provides the method getSystemService which allows to receive a manager object for the different hardware parts. As Activities and Services extend this class you can directly access the context via "this".

2. Installation

The following assume that you have already Eclipse installed. For details please see Eclipse Tutorial .

2.1. Android SDK

Download the Android SDK from the Android homepage under Android SDK download . The download contains a zip file which you can extract to any place in your file system, e.g. I placed it under "c:\android-sdk-windows" .

2.2. Eclipse

Use the Eclipse update manager to install all available plugins for the Android Development Tools (ADT) from the URL https://dl-ssl.google.com/android/eclipse/ .

2.3. Configuration

In Eclipse open the Preferences dialog via Windows -> Preferences. Select Android and maintain the installation path of the Android SDK.

Tip

If you maintain the location the Android plugin will remind you frequently (and for every workspace). Join me in starring at Bug 3210 to get this improved.

Select now Window -> Android SDK and AVD Manager from the menu.

Select available packages and select the latest version of the SDK.

Page 6: Android Development Tutorial

Press "Install selected" and confirm the license for all package. After the installation restart Eclipse.

2.4. Device

You need to define a device which can be used for emulation. Press the device manager button, press "New" and maintain the following.

Press "Create AVD".This will create the device. To test if you setup is correct, eelect your device and press "Start".

After (a long time) your device should be started.

3. Error handling

Things are not always working as they should be. Several users report that get the following errors:

1. Project ... is missing required source folder: 'gen' 2. The project could not be built until build path errors are resolved. 3. Unable to open class file R.java.

To solve this error select from the menu Project -> Clean.

If you having problems with your own code you can use the LogCat viewer as described in LogCat Viewer .

4. Your first Android project

4.1. Create Project

Tip

Page 7: Android Development Tutorial

This app is also available on the Android Marketplace. Search for "vogella" for find this example.

Select File -> New -> Other -> Android -> Android Project and create the Android project "de.vogella.android.temperature". Maintain the following.

Tip

I think this wizard should have the option to add the project to an existing working set. Please stare at Android New Project Wizard should have the option to add to Working set to get this functionality.

Press "Finish". This should create the following directory structure.

While "res" contains structured values which are known to the Android platform the directory "assets" can be used to store any kind of data. In Java you can access this data via the AssetsManager and the method getAssets().

4.2. Two faces of things

The Android SDK allows to maintain certain artifacts, e.g. strings and UI's, in two ways, via a rich editor and directly via XML. The following description tries to use the rich UI but for validation lists also the XML. You can switch between the two things the the tab on the lower part of the screen. For example:

4.3. Create attributes

Android allows to create attributes for resources, e.g. for strings and / or colors. These attributes can be used in your UI definition via XML or in your Java source code.

Select the file "res/values/string.xml" and press "Add". Select "Color" and maintain "myColor" as the name and "#3399CC" as the value.

Add also the following "String" attributes. String attributes allow to translate the application at a later point.

Table 1. String Attributes

Page 8: Android Development Tutorial

Name Value

buttonHandler myClickHandler

celsius to Celsius

fahrenheit to Fahrenheit

calc Calculate

Switch to the XML representation and validate that you maintained the values correctly.

<?xml version="1.0" encoding="utf-8"?><resources> <string name="hello">Hello World, Convert!</string> <string name="app_name">Temperature Converter</string> <color name="myColor">#3399CC</color> <string name="buttonHandler">myClickHandler</string> <string name="celsius">to Celsius</string> <string name="fahrenheit">to Fahrenheit</string> <string name="calc">Calculate</string></resources>

4.4. Add UI Elements

Select "res/layout/main.xml" and open the Android editor via double-click. This editor allows to maintain the UI via drag and drop or directly via the XML source code. You can switch between both representations via the tabs at the bottom of the editor. For changing the postion and grouping elements you can use the outline view.

Delete the "Hello World, Hello!" via a right mouse click. From the "Views" bar, drag in an "EditText". Add from the layout a "RadioGroup" and then two RadioButtons, add one "Button". The result should look like the following and the corresponding XML is listed below. Make sure that your code is the same as listed below.

Switch to "main.xml" and verify that your XML looks like the following.

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent">

<EditText android:text="@+id/EditText01" android:id="@+id/EditText01" android:layout_width="wrap_content" android:layout_height="wrap_content"></EditText> <RadioGroup android:id="@+id/RadioGroup01"

Page 9: Android Development Tutorial

android:layout_width="wrap_content" android:layout_height="wrap_content"> <RadioButton android:text="@+id/RadioButton01" android:id="@+id/RadioButton01" android:layout_width="wrap_content" android:layout_height="wrap_content"></RadioButton> <RadioButton android:text="@+id/RadioButton02" android:id="@+id/RadioButton02" android:layout_width="wrap_content" android:layout_height="wrap_content"></RadioButton> </RadioGroup> <Button android:text="@+id/Button01" android:id="@+id/Button01" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button></LinearLayout>

4.5. Maintain UI properties

If you select a UI element you can change its properties via the properties view. Select EditText and change the property "Layout Width" to "fill_parent".

Assign the "celsius" string attribute to your "text" property of the first radio button and "fahrenheit" to the second. Set the property "Checked" to true for the first RadioButton. Assign "calc" to the text property of your button and assign "buttonHandler" to the "onClick" property. Delete the text property in the EditText (this means no text will be initially shown) and set the "Input type" property to "numberSigned" and "number decimal".

Select the complete widget and use the Properties view to set the property "background" to the color attribute "@color/myColor".

Switch to the "main.xml" tab and verify that the XML is correctly maintained.

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@color/myColor">

<EditText android:id="@+id/EditText01" android:layout_height="wrap_content" android:layout_width="fill_parent" android:inputType="numberSigned|numberDecimal"></EditText> <RadioGroup android:id="@+id/RadioGroup01" android:layout_width="wrap_content" android:layout_height="wrap_content"> <RadioButton android:id="@+id/RadioButton01"

Page 10: Android Development Tutorial

android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/celsius" android:checked="true"></RadioButton> <RadioButton android:id="@+id/RadioButton02" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/fahrenheit"></RadioButton> </RadioGroup> <Button android:id="@+id/Button01" android:layout_height="wrap_content" android:onClick="@string/buttonHandler" android:layout_width="wrap_content" android:text="@string/calc"></Button></LinearLayout>

4.6. Code your application

Change your code in "Convert.java" to the following. Note that the "myClickHandler" will be called based on the "On Click" property of your button.

package de.vogella.android.temperature;

import android.app.Activity;import android.os.Bundle;import android.view.View;import android.widget.EditText;import android.widget.RadioButton;import android.widget.Toast;

public class Convert extends Activity { private EditText text;

@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); text = (EditText) findViewById(R.id.EditText01);

}

// This method is called at button click because we assigned the name to the // "On Click property" of the button public void myClickHandler(View view) { switch (view.getId()) { case R.id.Button01: RadioButton celsiusButton = (RadioButton) findViewById(R.id.RadioButton01); RadioButton fahrenheitButton = (RadioButton) findViewById(R.id.RadioButton02); if (text.getText().length() == 0) { Toast.makeText( this, "Please enter a valid number", Toast.LENGTH_LONG).show(); return; }

Page 11: Android Development Tutorial

float inputValue = Float.parseFloat(text.getText().toString()); if (celsiusButton.isChecked()) { text.setText(String .valueOf(convertFahrenheitToCelcius(inputValue))); } else { text.setText(String .valueOf(convertCelciusToFahrenheit(inputValue))); } // Switch to the other button if (fahrenheitButton.isChecked()) { fahrenheitButton.setChecked(false); celsiusButton.setChecked(true); } else { fahrenheitButton.setChecked(true); celsiusButton.setChecked(false); } break; } }

// Converts to celcius private float convertFahrenheitToCelcius(float fahrenheit) { return ((fahrenheit - 32) * 5 / 9); }

// Converts to fahrenheit private float convertCelciusToFahrenheit(float celsius) { return ((celsius * 9) / 5) + 32; }}

4.7. Start Project

To start the Android Application, select your project, right click on it, Run-As-> Android Application Be patient, the emulator starts up very slow. You should get the following result.

Type in a number, select your conversion and press the button. The result should be displayed and the other option should get selected.

4.8. Using the home menue

If you press the Home button you can also select your application.

Page 12: Android Development Tutorial

5. Lists

5.1. Overview

List can be used to display a scrollable list of items. You can either use lists in your layout or if the purpose of your Activity is to show primary a list you can extend ListActivities which provides nice hocks for typical actions for lists.

5.2. Simple ListActivities

A ListActivity extends Activity and simplifies the approach to show several objects in a list. It extends the standard Activity with a standard ListView Elements, callbacks for list events, e..g for selecting a list element and helper methods to access the current list position and the selected element(s).

To test this create a new Android project "de.vogella.android.listactivity" with the activity "MyList". You do not need to change the default layout "main.xml". Create the following activity.

package de.vogella.android.listactivity;

import android.app.ListActivity;import android.os.Bundle;import android.view.View;import android.widget.ArrayAdapter;import android.widget.ListView;import android.widget.Toast;

public class MyList extends ListActivity {

/** Called when the activity is first created. */ public void onCreate(Bundle icicle) { super.onCreate(icicle); // Create an array of Strings, that will be put to our ListActivity String[] names = new String[] { "Linux", "Windows7", "Eclipse", "Suse", "Ubuntu", "Solaris", "Android", "iPhone"}; // Create an ArrayAdapter, that will actually make the Strings above // appear in the ListView this.setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_checked, names)); }

@Override protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); // Get the item that was clicked Object o = this.getListAdapter().getItem(position); String keyword = o.toString(); Toast.makeText(this, "You selected: " + keyword, Toast.LENGTH_LONG) .show(); }

Page 13: Android Development Tutorial

}

5.3. ListActivities with own layout

The example above is boring, as only text is shown. You can also define your own layout for the rows and assign this layout to your row adapter. We will add a graphic to each list entry.

Create the following layout file "rowlayout.xml" in the res/layout folder of your project "de.vogella.android.listactivity".

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content"> <ImageView android:id="@+id/icon" android:layout_height="wrap_content" android:src="@drawable/icon" android:layout_width="22px" android:layout_marginTop="4px" android:layout_marginRight="4px" android:layout_marginLeft="4px"> </ImageView> <TextView android:text="@+id/TextView01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/label" android:textSize="30px"></TextView></LinearLayout>

Change your activity "MyList" to the following. This is almost the same coding as in the previous example, the only difference is that we are using our own layout in the ArrayAdapter and telling the adapter which UI element should contains the text.

package de.vogella.android.listactivity2;

import android.app.Activity;import android.app.ListActivity;import android.os.Bundle;import android.view.View;import android.widget.ArrayAdapter;import android.widget.ListView;import android.widget.Toast;

public class MyLayoutList extends ListActivity {

/** Called when the activity is first created. */ public void onCreate(Bundle icicle) { super.onCreate(icicle); // Create an array of Strings, that will be put to our ListActivity String[] names = new String[] { "Linux", "Windows7", "Eclipse", "Suse",

Page 14: Android Development Tutorial

"Ubuntu", "Solaris", "Android", "iPhone" }; // Use your own layout and point the adapter to the UI elements which contains the label this.setListAdapter(new ArrayAdapter<String>(this, R.layout.rowlayout, R.id.label, names)); }

@Override protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); // Get the item that was clicked Object o = this.getListAdapter().getItem(position); String keyword = o.toString(); Toast.makeText(this, "You selected: " + keyword, Toast.LENGTH_LONG) .show();

}}

5.4. ListActivities with flexible layout

The above example uses one layout for all rows. If you want to influence the display of the different rows you can also define your own adapter and implement your own getView() method. This method is responsible for creating the listview. In this method we will read the pre-defined layout via LayoutInflator and return one individual view per row.

Create the following class "MyArrayAdapter.java".

package de.vogella.android.listactivity;

import android.app.Activity;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ArrayAdapter;import android.widget.ImageView;import android.widget.TextView;

public class MyArrayAdapter extends ArrayAdapter<String> { private final Activity context; private final String[] names;

public MyArrayAdapter(Activity context, String[] names) { super(context, R.layout.rowlayout, names); this.context = context; this.names = names; }

@Override

Page 15: Android Development Tutorial

public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = context.getLayoutInflater(); View rowView = inflater.inflate(R.layout.rowlayout, null, true); TextView label = (TextView) rowView.findViewById(R.id.label); label.setText(names[position]); System.out.println(names[position]); // Change the icon for Windows and iPhone if (names[position].startsWith("Windows7") || names[position].startsWith("iPhone") ) { ImageView imageView = (ImageView) rowView.findViewById(R.id.icon); imageView.setImageResource(R.drawable.alt_window_16); } return rowView; }

}

package de.vogella.android.listactivity;

import android.app.ListActivity;import android.os.Bundle;import android.view.View;import android.widget.ListView;import android.widget.Toast;

public class MyList extends ListActivity {

/** Called when the activity is first created. */ public void onCreate(Bundle icicle) { super.onCreate(icicle); // Create an array of Strings, that will be put to our ListActivity String[] names = new String[] { "Linux", "Windows7", "Eclipse", "Suse", "Ubuntu", "Solaris", "Android", "iPhone"}; this.setListAdapter(new MyArrayAdapter(this, names)); }

@Override protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); // Get the item that was clicked Object o = this.getListAdapter().getItem(position); String keyword = o.toString(); Toast.makeText(this, "You selected: " + keyword, Toast.LENGTH_LONG) .show(); }}

Page 16: Android Development Tutorial

6. Menu, Preferences and Intents

6.1. Project

This chapter will demonstrate how to create and evaluate a menu, how to define preferences and how to navigate between activities via an intent . Create a project "de.vogella.android.preferences" with the activity "HelloPreferences". Change the UI in the file "/res/layout/main.xml" to the following:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <Button android:id="@+id/Button01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Show Preferences"></Button></LinearLayout>

6.2. Add a menu

Menus can be defined via XML files. Select your project, right click on it and select New -> Other -> Android -> "Android XML File".

Press Add and select "Item". Maintain the following value. This defines the entries in your menu. We will have only one entry.

Change your class "HelloPreferences" to the following. The OnCreateOptionsMenu method is used to create the menu. Please note that at the moment nothing happens if you select this menu. The behavior will be later implemented in the method "onOptionsItemSelected".

package de.vogella.android.preferences;

import android.app.Activity;import android.os.Bundle;import android.view.Menu;import android.view.MenuInflater;

Page 17: Android Development Tutorial

public class HelloPreferences extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu, menu); return true; }}

Run your application and press "Menu" on the emulator. Your menu should be displayed.

6.3. Using preferences

Preference values can also be stored as a XML resource. Create another Android XML File "preferences.xml" this time of type preferences.

Press Add, add a category and add two preferences "EditTextPreferences" to this category : "User" and "Password".

Create the class "Preferences" which will load the "preference.xml".

package de.vogella.android.preferences;

import android.os.Bundle;import android.preference.PreferenceActivity;

public class Preferences extends PreferenceActivity {

/** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); }

Page 18: Android Development Tutorial

}

Select "AndroidManifest.xml" and the tab "Application". Add the activity "Preferences".

To use the preferences add a button to your main.xml with the id "@+id/Button01" and change the coding of HelloPreferences to the following.

package de.vogella.android.preferences;

import android.app.Activity;import android.content.Intent;import android.content.SharedPreferences;import android.os.Bundle;import android.preference.PreferenceManager;import android.view.Menu;import android.view.MenuInflater;import android.view.MenuItem;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.Toast;

public class HelloPreferences extends Activity { SharedPreferences preferences;

/** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button button = (Button) findViewById(R.id.Button01); // Initialize preferences preferences = PreferenceManager.getDefaultSharedPreferences(this); button.setOnClickListener(new OnClickListener() {

@Override public void onClick(View v) { String username = preferences.getString("username", "n/a"); String password = preferences.getString("password", "n/a"); Toast.makeText(HelloPreferences.this, "You maintained user: " + username + " and password: " + password, Toast.LENGTH_LONG).show();

Page 19: Android Development Tutorial

} }); }

@Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu, menu); return true; }

// This method is called once the menu is selected @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { // We have only one menu option case R.id.preferences: // Launch Preference activity Intent i = new Intent(HelloPreferences.this, Preferences.class); startActivity(i); // A toast is a view containing a quick little message for the user. Toast.makeText(HelloPreferences.this, "Here you can maintain your user credentials.", Toast.LENGTH_LONG).show(); break;

} return true; }}

6.4. Run

Run your application. Press the "menu" hardware button and then select your menu item "Preferences". You should be able to enter your user settings then press the back hardware button to return to your main activity and press the button. The saved values should be displayed in a small message windows (Toast).

7. ContentProvider

7.1. Overview

ContentProvider are used to provide data from an application to another. ContentProvider do not store the data but provide the interface for other applications to access the data.

Page 20: Android Development Tutorial

The following example will use an existing context provider from "Contacts".

7.2. Create contacts on your emulator

Select the home menu and then the menu entry "Contacts" to create contacts.

Press Menu and select "New Contact".

As a result you should have a few new contacts.

7.3. Example

Create a new Android project "de.vogella.android.contentprovider" with the activity "ContactsView".

Rename the id of the the existing TextView from the example wizard to "contactview". Delete the default text. Also change the layout_height to "fill_parent".

The resulting main.xml should look like the following.

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/contactview" /></LinearLayout>

In AndroidManifest.xml add the User Permission that the application can use "android.permission.READ_CONTACTS".

Change the coding of the activity.

package de.vogella.android.contentprovider;

import android.app.Activity;import android.database.Cursor;import android.net.Uri;

Page 21: Android Development Tutorial

import android.os.Bundle;import android.provider.ContactsContract;import android.widget.TextView;

public class ContactsView extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); TextView contactView = (TextView) findViewById(R.id.contactview);

Cursor cursor = getContacts();

while (cursor.moveToNext()) {

String displayName = cursor.getString(cursor .getColumnIndex(ContactsContract.Data.DISPLAY_NAME)); contactView.append("Name: "); contactView.append(displayName); contactView.append("\n"); } }

private Cursor getContacts() { // Run query Uri uri = ContactsContract.Contacts.CONTENT_URI; String[] projection = new String[] { ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME }; String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '" + ("1") + "'"; String[] selectionArgs = null; String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";

return managedQuery(uri, projection, selection, selectionArgs, sortOrder); }

}

8. ScrollView

ScrollViews can be used to contain one child that might be to big to fit on one screen. If the child is to big the ScrollView will display a scroll bar to scroll the context. Of course the child can be a layout which can then contain other elements.

Create an android project "de.vogella.android.scrollview" with the activity "ScrollView". Create the following layout and class.

Page 22: Android Development Tutorial

<?xml version="1.0" encoding="utf-8"?><ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:fillViewport="true">

<LinearLayout android:id="@+id/LinearLayout01" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="wrap_content"> <TextView android:id="@+id/TextView01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="This is a header" android:textAppearance="?android:attr/textAppearanceLarge" android:paddingLeft="8dip" android:paddingRight="8dip" android:paddingTop="8dip"></TextView> <TextView android:text="@+id/TextView02" android:id="@+id/TextView02" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_weight="1.0"></TextView> <LinearLayout android:id="@+id/LinearLayout02" android:layout_width="wrap_content" android:layout_height="wrap_content"> <Button android:id="@+id/Button01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Submit" android:layout_weight="1.0"></Button> <Button android:id="@+id/Button02" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Cancel" android:layout_weight="1.0"></Button> </LinearLayout></LinearLayout></ScrollView>

package de.vogella.android.scrollview;

import android.app.Activity;import android.os.Bundle;import android.view.View;import android.widget.TextView;

public class ScrollView extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); TextView view = (TextView) findViewById(R.id.TextView02); String s=""; for (int i=0; i < 100; i++) { s += "vogella.de "; } view.setText(s); }

Page 23: Android Development Tutorial

}

The attribute "android:fillViewport="true"" ensures that the the scrollview is set to the full screen even if the elements are smaller then one screen and the "layout_weight" tell the android system that these elements should be extended.

9. Services and Broadcast Receiver

The Android platform provides a lot of pre-defined services, usually exposed via a Manager class. In this chapter we will use the AlertManager and VibratorManager. The alarm manager will in our example our own broadcast receiver.

Create a new project "de.vogella.android.alarm" with the activity "AlarmActivity". Create the following layout.

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent">

<EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/time" android:hint="Number of seconds" android:inputType="numberDecimal"></EditText><Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/ok" android:onClick="startAlert" android:text="Start Counter"></Button>

</LinearLayout>

Create the following broadcast receiver class. This class will get the Vibrator service.

package de.vogella.android.alarm;

import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.os.Vibrator;import android.widget.Toast;

public class MyBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Toast.makeText(context, "Don't panik but your time is up!!!!.",

Page 24: Android Development Tutorial

Toast.LENGTH_LONG).show(); // Vibrate the mobile phone Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE); vibrator.vibrate(2000); }

}

Maintain this class as broadcast receiver in "AndroidManifest.mf" and allow the vibrate authorization.

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="de.vogella.android.alarm" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".AlarmActivity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <receiver android:name=".MyBroadcastReceiver" android:enabled="true"> </receiver> </application> <uses-sdk android:minSdkVersion="8" />

<uses-permission android:name="android.permission.VIBRATE"></uses-permission></manifest>

Now define your main Activitiy. This activity will create an Intent for the Broadcast receiver and get the AlarmManager service.

package de.vogella.android.alarm;

import android.app.Activity;import android.app.AlarmManager;import android.app.PendingIntent;import android.content.Intent;import android.os.Bundle;import android.view.View;import android.widget.EditText;import android.widget.Toast;

Page 25: Android Development Tutorial

public class AlarmActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); }

public void startAlert(View view) { EditText text = (EditText) findViewById(R.id.time); int i = Integer.parseInt(text.getText().toString()); Intent intent = new Intent(this, MyBroadcastReceiver.class); PendingIntent pendingIntent = PendingIntent.getBroadcast( this.getApplicationContext(), 234324243, intent, 0); AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (i * 1000), pendingIntent); Toast.makeText(this, "Alarm set in " + i + " seconds", Toast.LENGTH_LONG).show(); }

}

10. Important views

10.1. LogCat View

You can see the log (including System.out.print() statements) via the LogCat view.

10.2. File explorer

The file explorer allows to see the files on the android simulator.

11. Shell

11.1. Android Debugging Bridge - Shell

You can access your Android emulator also via the console. Open a shell, switch to your "android-sdk" installation directory into the folder "tools". Start the shell via the following command "adb shell".

adb shell

Page 26: Android Development Tutorial

This will connect you to your device and give you Linux command line access to the underlying file system, e.g. ls, rm, mkdir, etc. The application data is stored in the directory "/data/data/package_of_your_app".

If you have several devices running you can issue commands to one individuel device.

# Lists all devicesadb devices#ResultList of devices attachedemulator-5554 attachedemulator-5555 attached# Issue a command to a specific deviceadb -s emulator-5554 shell

11.2. Uninstall an application via adb

You can uninstall an android application via the shell. Switch the the data/app directory (cd /data/app) and simply delete your android application.

11.3. Emulator Console via telnet

Alternatively to adb you can also use telnet to connect to the device. This allows you to simulate certain things, e.g. incoming call, change the network "stability", set your current geocodes, etc. Use "telnet localhost 5554" to conntect to your simulated device. To exit the console session, use the command "quit" or "exit".

For example to change the power settings of your phone, to receive an sms and to get an incoming call make the following.

# connects to devicetelnet localhost 5554# set the power levelpower status fullpower status charging# make a call to the devicegsm call 012041293123# send a sms to the devicesms send 12345 Will be home soon# set the geo location

For more information on the emulator console please see Emulator Console manual

12. Deploy your application on a real device

Page 27: Android Development Tutorial

Turn on "USB Debugging" on your device in the settings. Select in the settings Applications > Development, then enable USB debugging. You also need to install the driver for your mobile phone. For details please see Developing on a Device . Please note that the Android version you are developing for must be the installed version on your phone.

To select your phone, select the "Run Configurations", select "Manual" selection and select your device.

13. Thank you