Curso de Android - VoxIsland

67
ANDROID TUTORIAL http://android.voxisland.com (c) 2010 VoxIsland Training companion 1

Transcript of Curso de Android - VoxIsland

Page 1: Curso de Android - VoxIsland

ANDROIDTUTORIAL

http://android.voxisland.com(c) 2010 VoxIsland

Training companion

1

Page 2: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 2: Getting to know AndroidHistory

In July 2005, Google acquired Android, Inc., a small startup company based in Palo Alto, California, USA. Android's co-founders who went to work at Google included Andy Rubin (co-founder of Danger), Rich Miner (co-founder of Wildfire Communications, Inc.), Nick Sears (once VP at T-Mobile), and Chris White (headed design and interface development at WebTV). At the time, little was known about the functions of Android, Inc. other than that they made software for mobile phones. This began rumors that Google was planning to enter the mobile phone market.At Google, the team led by Rubin developed a mobile device platform powered by the Linux kernel which they marketed to handset makers and carriers on the premise of providing a flexible, upgradeable system.[citation needed] It was reported that Google had already lined up a series of hardware component and software partners and signaled to carriers that it was open to various degrees of cooperation on their part. More speculation that Google would be entering the mobile-phone market came in December 2006. Reports from the BBC and The Wall Street Journal noted that Google wanted its search and applications on mobile phones and it was working hard to deliver that. Print and online media outlets soon reported rumors that Google was developing a Google-branded handset. More speculation followed reporting that as Google was defining technical specifications, it was showing prototypes to cell phone manufacturers and network operators.Ultimately Google unveiled its smartphone Nexus One that uses the Android open source mobile operating system. The device is manufactured by Taiwan's HTC Corporation, and became available on January 5, 2010.

source: wikipedia

2

Page 3: Curso de Android - VoxIsland

The Open Handset Alliance

founding members in bold

as of 03-2010

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 2: Getting to know Android

Mobile Operators

SoftwareCompanies

CommercializationCompanies

SemiconductorsCompanies

Handset Manufacturers

China MobileKDDI Corporation

NTT DoCoMoSprint Nextel

T-MobileTelecom Italia

Telefonica

VodafoneSoftbank

China Unicom

Ascender CorporationeBay

EsmertecGoogle

LivingImageMyriad Group|MyriadNMS Communications

Nuance Communications

PacketVideoSkyPop

SONiVOX

SVox

AplixNoser Engineering

The Astonishing TribeWind River Systems

BorqsOmron SW

TelecaSasken Comm Tech Ltd

AudienceBroadcom Corporation

Intel CorporationMarvell Technology

GroupNvidia Corporation

QualcommSiRF|SiRF Technology

HoldingsSynaptics

Texas Instruments

BorqsOmron SW

TelecaSasken Comm Tech Ltd

High Tech Computer Corporation|HTC

LGMotorola

Samsung Electronics

ASUSTekGarmin

Huawei TechSony Ericsson

ToshibaAcer

3

Page 4: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 2: Getting to know Android

Android application development VS traductionnal development

1. Limited resources will slow-down developments

2. Re-Usability of components (mashups) will speed-up developments

3. Interchangeable apps

will speed-up developments

LIMITATIONS Computer Android phone

Power

Screen

CPU

Memory

Storage

no need to addresslimiting power consumption is

crucial

big display small display

Ghz hunders of Mhz

Gb Mb

Tb or Gb Gb or Mb

4

Page 5: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 3: Android development setup

4 download and install steps:

Java SDK http://developers.sun.com/downloads/

Eclipse

http://www.eclipse.org/downloads/

Android SDK http://developer.android.com/sdk/index.html

ADT https://dl-ssl.google.com/android/eclipse

5

Page 6: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 3: Android development setupAdding the Android SDK tools to your system's PATH:

MAC OS go in your home directory edit (or create) .bash_profile add the complete path to tools in the PATH variable (coma separated) example: export PATH=${PATH}:/Developer/android-sdk-mac_86/tools/

GNU/LINUX

go in your home directory edit .bash_profile or .bash_rc add the complete path to tools in the PATH variable (coma separated) example: export PATH=${PATH}:/Developer/android-sdk-mac_86/tools/

WINDOWS Explorer - right click on My Computer - click on Properties - click on Advanced tab - click on Environment

variable - double click on PATH - adding the path to tools in the variable

6

Page 7: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 4: Android development with Eclipse

BabySteps project:

package com.voxisland;

import android.app.Activity;import android.os.Bundle;

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

7

Page 8: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 4: Android development with EclipseJAVA perspective:

8

Page 9: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 4: Android development with EclipseDDMS perspective:

9

Page 10: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 4: Android development with EclipseDEBUG perspective:

10

Page 11: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 5: Hello Android project structureR.java class:

/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */

package com.voxisland;

public final class R { public static final class attr { } public static final class drawable { public static final int icon=0x7f020000; } public static final class layout { public static final int main=0x7f030000; } public static final class string { public static final int app_name=0x7f040001; public static final int hello=0x7f040000; }}

11

Page 12: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 5: Hello Android project structureAndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.voxisland" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".BabySteps" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity>

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

</manifest>

12

Page 13: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 5: Hello Android project structuremain.xml (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" ><TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /><Button android:text="@+id/Button01" android:id="@+id/Button01" android:layout_width="fill_parent" android:layout_height="wrap_content"></Button><Button android:text="hello" android:id="@+id/Button02" android:layout_width="fill_parent" android:layout_height="wrap_content"></Button></LinearLayout>

13

Page 14: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 5: Hello Android project structure

strings.xml:

<?xml version="1.0" encoding="utf-8"?><resources> <string name="hello">Hello Chapter 4!</string> <string name="app_name">Baby Steps</string></resources>

14

Page 15: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 5: Hello Android project structureAndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.voxisland" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".BabySteps" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity>

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

</manifest>

15

Page 16: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 6,7,8: The Joshua ProjectThe project once completed:

16

Page 17: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 6,7,8: The Joshua ProjectLayout:

<?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="wrap_content" android:id="@+id/myMessage" android:text="@string/hello" />

<LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" >

<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/myButton" android:text="@string/answer" /> <CheckBox android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/iSpeakFrench" android:text="Je parle Français" android:checked="false" android:textSize="5pt"/>

</LinearLayout>

<LinearLayout android:layout_width="fill_parent" android:layout_height="20px" android:orientation="horizontal">

<TextView android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1" android:gravity="center" android:background="#ff0000" android:textColor="#000000" android:text="red" /> <TextView android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1" android:gravity="center" android:background="#00ff00" android:textColor="#000000" android:text="green" />

<TextView android:layout_width="fill_parent"

android:layout_height="fill_parent" android:layout_weight="1" android:gravity="center" android:background="#0000ff" android:textColor="#000000" android:text="blue" /></LinearLayout>

<RadioGroup android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/myRadioGroup" android:orientation="horizontal">

<RadioButton android:layout_width="fill_parent"

android:layout_height="fill_parent" android:layout_marginLeft="35dp" android:layout_weight="1" android:id="@+id/myRadioButtonRed"/> <RadioButton android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_marginLeft="35dp" android:layout_weight="1" android:id="@+id/myRadioButtonGreen"/> <RadioButton android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_marginLeft="35dp" android:layout_weight="1" android:id="@+id/myRadioButtonBlue"/></RadioGroup>

</LinearLayout>

A

B

C

D

E

F

G

H

I

J

K

L

M

17

Page 18: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 6,7,8: The Joshua ProjectLayout:

B

C

D E

F

G H I

JK L M

A

18

Page 19: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 6,7,8: The Joshua Project

package com.voxisland;

import android.app.Activity;import android.graphics.Color;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.CheckBox;import android.widget.RadioButton;import android.widget.TextView;import android.widget.Toast;

public class Joshua extends Activity {

TextView myMessage; OnClickListener myRadioClickListener; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final Button myButton=(Button)findViewById(R.id.myButton);

final CheckBox iSpeakFrench=(CheckBox)findViewById(R.id.iSpeakFrench); iSpeakFrench.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { CheckBox v2=(CheckBox)v; if (v2.isChecked()) { myButton.setText("Salut Joshua"); } else { myButton.setText("Hello Joshua"); } } } ); myButton.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { if (iSpeakFrench.isChecked()) { Toast.makeText(Joshua.this, R.string.joshuareponse, Toast.LENGTH_LONG).show(); } else { Toast.makeText(Joshua.this, R.string.joshuaanswer, Toast.LENGTH_LONG).show(); } } }); myMessage=(TextView)findViewById(R.id.myMessage); myRadioClickListener=new OnClickListener() { @Override public void onClick(View v) { RadioButton myRadioButton=(RadioButton)v;

switch(myRadioButton.getId()) { case R.id.myRadioButtonRed: myMessage.setTextColor(Color.RED); break; case R.id.myRadioButtonGreen: myMessage.setTextColor(Color.GREEN); break; case R.id.myRadioButtonBlue: myMessage.setTextColor(Color.BLUE); break; } } }; RadioButton rbred, rbgreen,rbblue; rbred=(RadioButton)findViewById(R.id.myRadioButtonRed); rbgreen=(RadioButton)findViewById(R.id.myRadioButtonGreen); rbblue=(RadioButton)findViewById(R.id.myRadioButtonBlue); rbred.setOnClickListener(myRadioClickListener); rbgreen.setOnClickListener(myRadioClickListener); rbblue.setOnClickListener(myRadioClickListener); }}

Joshua class:

19

Page 20: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 9: ListsSimpleList class (1/2):

package com.voxisland;

import java.util.ArrayList;import java.util.Arrays;

import android.app.AlertDialog;import android.app.ListActivity;import android.content.Context;import android.content.DialogInterface;import android.os.Bundle;import android.view.View;import android.widget.AdapterView;import android.widget.ArrayAdapter;import android.widget.AdapterView.OnItemLongClickListener;

public class SimpleList extends ListActivity { String[] firstNames = { "Abigail", "Alexander", "Alexis", "Alyssa", "Andrew", "Anna", "Anthony", "Ashley", "Austin", "Ava", "Benjamin", "Brandon", "Brianna", "Caleb", "Chloe", "Christian", "Christopher", "Daniel", "David", "Destiny", "Dylan", "Elijah", "Elizabeth", "Emma", "Ethan", "Gabriel", "Grace", "Hailey", "Hannah", "Isabella", "James", "Jasmine", "Jennifer", "Jessica", "John", "Jonathan", "Jose", "Joseph", "Joshua", "Julia", "Justin", "Kaitlyn", "Katherine", "Kayla", "Kevin", "Lauren", "Logan", "Madison", "Matthew", "Megan", "Mia", "Michael", "Morgan", "Natalie", "Nathan", "Nicholas", "Noah", "Olivia", "Rachel", "Robert", "Ryan", "Samantha", "Samuel", "Sarah", "Sophia", "Sydney", "Taylor", "Thomas", "Tyler", "Victoria", "William", "Zachary" };

ArrayAdapter<String> adapter; private String itemSelected; private final Context context = this;

20

Page 21: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 9: ListsSimpleList class (2/2):

@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); OnItemLongClickListener itemDelListener = new OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View arg1, int position, long arg3) { itemSelected=parent.getItemAtPosition(position).toString(); AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setMessage("Do you really want to delete "+itemSelected+"?"); builder.setCancelable(false); builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { adapter.remove(itemSelected); adapter.notifyDataSetChanged(); } }); builder.setNegativeButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); builder.show(); return false; } }; ArrayList<String> myList = new ArrayList<String>(Arrays.asList(firstNames)); adapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, myList); setListAdapter(adapter); getListView().setOnItemLongClickListener(itemDelListener); }}

21

Page 22: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 10: ListsArrayAdapter:A ListAdapter that manages a ListView backed by an array of arbitrary objects. By default this class expects that the provided resource id references a single TextView. If you want to use a more complex layout, use the constructors that also takes a field id. That field id should reference a TextView in the larger layout resource. However the TextView is referenced, it will be filled with the toString() of each object in the array. You can add lists or arrays of custom objects. Override the toString() method of your objects to determine what text will be displayed for the item in the list. To use something other than TextViews for the array display, for instance, ImageViews, or to have some of data besides toString() results fill the views, override getView(int, View, ViewGroup) to return the type of view you want.

Public MethodsPublic Methodsvoid add(T object)

Adds the specified object at the end of the array.void clear()

Remove all elements from the list.Context getContext()

Returns the context associated with this array adapter.int getCount()

View getDropDownView(int position, View convertView, ViewGroup parent)Get a View that displays in the drop down popup the data at the specified position in the data set.

Filter getFilter()Returns a filter that can be used to constrain data with a filtering pattern.

T getItem(int position)

long getItemId(int position)

int getPosition(T item)Returns the position of the specified item in the array.

View getView(int position, View convertView, ViewGroup parent)

void insert(T object, int index)Inserts the specified object at the specified index in the array.

void notifyDataSetChanged()Notifies the attached View that the underlying data has been changed and it should refresh itself.

void remove(T object)Removes the specified object from the array.

void setDropDownViewResource(int resource)Sets the layout resource to create the drop down views.

voidsetNotifyOnChange(boolean notifyOnChange)Control whether methods that change the list (add(T), insert(T, int), remove(T), clear()) automatically call notifyDataSetChanged().

void sort(Comparator<? super T> comparator)Sorts the content of this adapter using the specified comparator.

22

Page 23: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 10: Long clicksDefinition:The long click/touching is a gesture used on Android mobile devices. Long click/touching is touching an item and pressing for a few seconds. Long clicks/touches on applications allows you to move them to the desktop, and long touches on the desktop clock allow you to remove it.

getListView().setOnItemLongClickListener(itemDelListener);

23

Page 24: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 11: Dialog boxesAdding a dialog box to the list example:

@Overridepublic boolean onItemLongClick(AdapterView<?> parent, View arg1, int position, long arg3) { itemSelected=parent.getItemAtPosition(position).toString(); AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setMessage("Do you really want to delete "+itemSelected+"?"); builder.setCancelable(false); builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { adapter.remove(itemSelected); adapter.notifyDataSetChanged(); } }); builder.setNegativeButton("No", new DialogInterface.OnClickListener() {

@Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); builder.show(); return false;}

24

Page 25: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 11: Dialog boxesAdding a dialog box to the list example:

@Overridepublic boolean onItemLongClick(AdapterView<?> parent, View arg1, int position, long arg3) { itemSelected=parent.getItemAtPosition(position).toString(); AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setMessage("Do you really want to delete "+itemSelected+"?"); builder.setCancelable(false); builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { adapter.remove(itemSelected); adapter.notifyDataSetChanged(); } }); builder.setNegativeButton("No", new DialogInterface.OnClickListener() {

@Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); builder.show(); return false;}

25

Page 26: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 11: Dialog boxes

Public MethodsPublic MethodsAlertDialog create()

Creates a AlertDialog with the arguments supplied to this builder.AlertDialog.Builder setAdapter(ListAdapter adapter, DialogInterface.OnClickListener listener)

Set a list of items, which are supplied by the given ListAdapter, to be displayed in the dialog as the content, you will be notified of the selected item via the supplied listener.

AlertDialog.Builder setCancelable(boolean cancelable)Sets whether the dialog is cancelable or not default is true.

AlertDialog.Builder setCursor(Cursor cursor, DialogInterface.OnClickListener listener, String labelColumn)Set a list of items, which are supplied by the given Cursor, to be displayed in the dialog as the content, you will be notified of the selected item via the supplied listener.

AlertDialog.Builder setCustomTitle(View customTitleView)Set the title using the custom view customTitleView.

AlertDialog.Builder setIcon(Drawable icon)Set the Drawable to be used in the title.

AlertDialog.Builder setIcon(int iconId)Set the resource id of the Drawable to be used in the title.

AlertDialog.Builder setInverseBackgroundForced(boolean useInverseBackground)Sets the Dialog to use the inverse background, regardless of what the contents is.

AlertDialog.Builder setItems(int itemsId, DialogInterface.OnClickListener listener)Set a list of items to be displayed in the dialog as the content, you will be notified of the selected item via the supplied listener.

AlertDialog.Builder setItems(CharSequence[] items, DialogInterface.OnClickListener listener)Set a list of items to be displayed in the dialog as the content, you will be notified of the selected item via the supplied listener.

AlertDialog.Builder setMessage(int messageId)Set the message to display using the given resource id.

AlertDialog builder 1/3:

26

Page 27: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 11: Dialog boxes

AlertDialog.Builder setMessage(CharSequence message)Set the message to display.

AlertDialog.Builder setMultiChoiceItems(Cursor cursor, String isCheckedColumn, String labelColumn, DialogInterface.OnMultiChoiceClickListener listener)Set a list of items to be displayed in the dialog as the content, you will be notified of the selected item via the supplied listener.

AlertDialog.Builder setMultiChoiceItems(int itemsId, boolean[] checkedItems, DialogInterface.OnMultiChoiceClickListener listener)Set a list of items to be displayed in the dialog as the content, you will be notified of the selected item via the supplied listener.

AlertDialog.Builder setMultiChoiceItems(CharSequence[] items, boolean[] checkedItems, DialogInterface.OnMultiChoiceClickListener listener)Set a list of items to be displayed in the dialog as the content, you will be notified of the selected item via the supplied listener.

AlertDialog.Builder setNegativeButton(CharSequence text, DialogInterface.OnClickListener listener)Set a listener to be invoked when the negative button of the dialog is pressed.

AlertDialog.Builder setNegativeButton(int textId, DialogInterface.OnClickListener listener)Set a listener to be invoked when the negative button of the dialog is pressed.

AlertDialog.Builder setNeutralButton(int textId, DialogInterface.OnClickListener listener)Set a listener to be invoked when the neutral button of the dialog is pressed.

AlertDialog.Builder setNeutralButton(CharSequence text, DialogInterface.OnClickListener listener)Set a listener to be invoked when the neutral button of the dialog is pressed.

AlertDialog.Builder setOnCancelListener(DialogInterface.OnCancelListener onCancelListener)Sets the callback that will be called if the dialog is canceled.

AlertDialog.Builder setOnItemSelectedListener(AdapterView.OnItemSelectedListener listener)Sets a listener to be invoked when an item in the list is selected.

AlertDialog.Builder setOnKeyListener(DialogInterface.OnKeyListener onKeyListener)Sets the callback that will be called if a key is dispatched to the dialog.

AlertDialog builder 2/3:

27

Page 28: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 11: Dialog boxes

AlertDialog.Builder setPositiveButton(CharSequence text, DialogInterface.OnClickListener listener)Set a listener to be invoked when the positive button of the dialog is pressed.

AlertDialog.Builder setPositiveButton(int textId, DialogInterface.OnClickListener listener)Set a listener to be invoked when the positive button of the dialog is pressed.

AlertDialog.Builder setSingleChoiceItems(int itemsId, int checkedItem, DialogInterface.OnClickListener listener)Set a list of items to be displayed in the dialog as the content, you will be notified of the selected item via the supplied listener.

AlertDialog.Builder setSingleChoiceItems(CharSequence[] items, int checkedItem, DialogInterface.OnClickListener listener)Set a list of items to be displayed in the dialog as the content, you will be notified of the selected item via the supplied listener.

AlertDialog.Builder setSingleChoiceItems(ListAdapter adapter, int checkedItem, DialogInterface.OnClickListener listener)Set a list of items to be displayed in the dialog as the content, you will be notified of the selected item via the supplied listener.

AlertDialog.Builder setSingleChoiceItems(Cursor cursor, int checkedItem, String labelColumn, DialogInterface.OnClickListener listener)Set a list of items to be displayed in the dialog as the content, you will be notified of the selected item via the supplied listener.

AlertDialog.Builder setTitle(int titleId)Set the title using the given resource id.

AlertDialog.Builder setTitle(CharSequence title)Set the title displayed in the Dialog.

AlertDialog.Builder setView(View view)Set a custom view to be the contents of the Dialog.

AlertDialog show()Creates a AlertDialog with the arguments supplied to this builder and show()'s the dialog.

AlertDialog builder 3/3:

28

Page 29: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 12: Intents 1Intents1 class 1/2:

package com.voxisland;

import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.view.View;import android.widget.Button;

public class Intents1 extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button myGalleryButton = (Button)findViewById(R.id.myGalleryButton); Button myCallLogButton = (Button)findViewById(R.id.myCallLogButton); Button myContactBookButton = (Button)findViewById(R.id.myContactBookButton); myGalleryButton.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { Intent myIntent = new Intent(); myIntent.setAction(Intent.ACTION_VIEW); myIntent.setData(android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI); startActivity(myIntent); } });

29

Page 30: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 12: Intents 1Intents1 class 2/2:

myCallLogButton.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { Intent myIntent = new Intent(); myIntent.setAction(Intent.ACTION_CALL_BUTTON); startActivity(myIntent); } }); myContactBookButton.setOnClickListener(new Button.OnClickListener() { @SuppressWarnings("deprecation") @Override public void onClick(View v) { Intent myIntent = new Intent(); myIntent.setAction(Intent.ACTION_VIEW); myIntent.setData(android.provider.Contacts.People.CONTENT_URI); startActivity(myIntent); } }); }}

30

Page 31: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 13: Intents 2Activity1 class:

package com.voxisland;

import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.view.View;import android.widget.Button;

public class Activity1 extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button button = (Button)findViewById(R.id.goto2); button.setOnClickListener(new Button.OnClickListener() {

@Override public void onClick(View v) { Intent intent = new Intent(v.getContext(), Activity2.class); startActivity(intent); } }); }}

31

Page 32: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 13: Intents 2Activity2 class:

package com.voxisland;

import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.view.View;import android.widget.Button;

public class Activity2 extends Activity{

@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main2); Button button = (Button)findViewById(R.id.goback); button.setOnClickListener(new Button.OnClickListener() {

@Override public void onClick(View v) { Intent intent = new Intent(); setResult(RESULT_OK, intent); finish(); } }); }}

32

Page 33: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 13: Intents 2Standard actions:

ACTION_MAINACTION_VIEWACTION_ATTACH_DATAACTION_EDITACTION_PICKACTION_CHOOSERACTION_GET_CONTENTACTION_DIALACTION_CALLACTION_SENDACTION_SENDTOACTION_ANSWERACTION_INSERTACTION_DELETEACTION_RUNACTION_SYNCACTION_PICK_ACTIVITYACTION_SEARCHACTION_WEB_SEARCHACTION_FACTORY_TEST

33

Page 34: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 13: Intents 2Standard boradcast actions:

ACTION_TIME_TICKACTION_TIME_CHANGEDACTION_TIMEZONE_CHANGEDACTION_BOOT_COMPLETEDACTION_PACKAGE_ADDEDACTION_PACKAGE_CHANGEDACTION_PACKAGE_REMOVEDACTION_PACKAGE_RESTARTEDACTION_PACKAGE_DATA_CLEAREDACTION_UID_REMOVEDACTION_BATTERY_CHANGEDACTION_POWER_CONNECTEDACTION_POWER_DISCONNECTEDACTION_SHUTDOWN

34

Page 35: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 13: Intents 2Standard boradcast actions:

ACTION_TIME_TICKACTION_TIME_CHANGEDACTION_TIMEZONE_CHANGEDACTION_BOOT_COMPLETEDACTION_PACKAGE_ADDEDACTION_PACKAGE_CHANGEDACTION_PACKAGE_REMOVEDACTION_PACKAGE_RESTARTEDACTION_PACKAGE_DATA_CLEAREDACTION_UID_REMOVEDACTION_BATTERY_CHANGEDACTION_POWER_CONNECTEDACTION_POWER_DISCONNECTEDACTION_SHUTDOWN

35

Page 36: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 13: Intents 2Standard categories:

CATEGORY_DEFAULTCATEGORY_BROWSABLECATEGORY_TABCATEGORY_ALTERNATIVECATEGORY_SELECTED_ALTERNATIVECATEGORY_LAUNCHERCATEGORY_INFOCATEGORY_HOMECATEGORY_PREFERENCECATEGORY_TESTCATEGORY_CAR_DOCKCATEGORY_DESK_DOCK

36

Page 37: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 13: Intents 2Standard extra data:

EXTRA_ALARM_COUNTEXTRA_BCCEXTRA_CCEXTRA_CHANGED_COMPONENT_NAMEEXTRA_DATA_REMOVEDEXTRA_DOCK_STATEEXTRA_DOCK_STATE_CAREXTRA_DOCK_STATE_DESKEXTRA_DOCK_STATE_UNDOCKEDEXTRA_DONT_KILL_APPEXTRA_EMAILEXTRA_INITIAL_INTENTSEXTRA_INTENTEXTRA_KEY_EVENT

EXTRA_PHONE_NUMBEREXTRA_REMOTE_INTENT_TOKENEXTRA_REPLACINGEXTRA_SHORTCUT_ICONEXTRA_SHORTCUT_ICON_RESOURCEEXTRA_SHORTCUT_INTENTEXTRA_STREAMEXTRA_SHORTCUT_NAMEEXTRA_SUBJECTEXTRA_TEMPLATEEXTRA_TEXTEXTRA_TITLEEXTRA_UID

37

Page 38: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 14: Option and Context menuspackage com.voxisland;

import android.app.Activity;import android.os.Bundle;import android.view.Menu;import android.view.MenuItem;import android.widget.TextView;

public class JAOptionsMenu extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } @Override public boolean onOptionsItemSelected(MenuItem item) { TextView tv = (TextView)findViewById(R.id.tv); tv.setText("YOU PUSHED ITEM #"+String.valueOf(item.getItemId())); return true; } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(0, Menu.FIRST, Menu.NONE, "ONE").setIcon(R.drawable.barcode); menu.add(0, Menu.FIRST+1, Menu.NONE, "TWO").setIcon(R.drawable.cards); menu.add(0, Menu.FIRST+2, Menu.NONE, "THREE").setIcon(R.drawable.chart); menu.add(0, Menu.FIRST+3, Menu.NONE, "FOUR").setIcon(R.drawable.clock); menu.add(0, Menu.FIRST+4, Menu.NONE, "FIVE").setIcon(R.drawable.cloud); menu.add(0, Menu.FIRST+5, Menu.NONE, "SIX").setIcon(R.drawable.dialog); menu.add(0, Menu.FIRST+6, Menu.NONE, "SEVEN").setIcon(R.drawable.dice); menu.add(0, Menu.FIRST+7, Menu.NONE, "HEIGHT").setIcon(R.drawable.disc); return true; }}

Options Menu

38

Page 39: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 14: Option and Context menuspackage com.voxisland;

import android.app.Activity;import android.os.Bundle;import android.view.ContextMenu;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.view.ContextMenu.ContextMenuInfo;import android.widget.TextView;import android.widget.Toast;

public class JAContextMenu extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); TextView tv = (TextView)findViewById(R.id.tv); tv.setOnCreateContextMenuListener(this); } @Override public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, view, menuInfo); menu.setHeaderTitle("Context menu"); menu.add(0, Menu.FIRST, Menu.NONE, "EDIT"); menu.add(0, Menu.FIRST+1, Menu.NONE, "DELETE"); menu.add(0, Menu.FIRST+2, Menu.NONE, "ADD"); } @Override public boolean onContextItemSelected(MenuItem item) { Toast.makeText(getApplicationContext(), item.getTitle().toString(), Toast.LENGTH_SHORT).show(); return true; }}

Context Menu

39

Page 40: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 15: Localization

1. Design your application

2. Choose your localization strategy: which countries, which languages?

3. Use no hard-coded strings or string constants; use R.string and strings.xml files.

4. Use no hard-coded drawables or layouts; use R.drawable and R.layout

5. Translate your strings files; localize your drawables.

6. Place your localized resources in the appropriate directories under 'res/'.

7. Create your final build or builds, using 'aapt' as necessary.

8. Upload your .apk file or files to Market, selecting the appropriate languages as you upload.

40

Page 41: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 16: Databases

package com.voxisland;

import android.app.Activity;import android.content.ContentValues;import android.content.Context;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.Toast;

public class MyDatabaseDemo extends Activity { private static final String DATABASE_NAME = "JADB.db"; private static final String DATABASE_TABLE = "myTable"; private static final String DATABASE_CREATE = "create table "+DATABASE_TABLE+" (_id integer primary key autoincrement, col1 text not null);"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button butCreate = (Button)findViewById(R.id.myButCreate); Button butAdd = (Button)findViewById(R.id.myButAdd); Button butCount = (Button)findViewById(R.id.myButCount); Button butShow = (Button)findViewById(R.id.myButShow);

// MORE HERE }}

41

Page 42: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 16: Databases

@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button butCreate = (Button)findViewById(R.id.myButCreate); Button butAdd = (Button)findViewById(R.id.myButAdd); Button butCount = (Button)findViewById(R.id.myButCount); Button butShow = (Button)findViewById(R.id.myButShow); butCreate.setOnClickListener(new OnClickListener() {

@Override public void onClick(View v) { SQLiteDatabase myDB; myDB = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null); myDB.execSQL(DATABASE_CREATE); myDB.close(); Toast.makeText(getApplicationContext(), "Table created", Toast.LENGTH_SHORT).show(); } });

42

Page 43: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 16: Databases

butAdd.setOnClickListener(new OnClickListener() {

@Override public void onClick(View v) { SQLiteDatabase myDB; myDB = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null); ContentValues newRow = new ContentValues(); newRow.put("col1", "ok"); myDB.insert(DATABASE_TABLE, null, newRow); myDB.close(); Toast.makeText(getApplicationContext(), "row added", Toast.LENGTH_SHORT).show(); } });

43

Page 44: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 16: Databases

butCount.setOnClickListener(new OnClickListener() {

@Override public void onClick(View v) { SQLiteDatabase myDB; myDB = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null); String[] resultColumns = new String[] {"_id", "col1"}; Cursor allRows = myDB.query(DATABASE_TABLE, resultColumns, null, null, null, null, null, null); Integer c = allRows.getCount(); myDB.close(); Toast.makeText(getApplicationContext(), "count: "+c.toString(), Toast.LENGTH_SHORT).show(); } });

44

Page 45: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 16: Databases

butShow.setOnClickListener(new OnClickListener() {

@Override public void onClick(View v) { SQLiteDatabase myDB; myDB = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null); String[] resultColumns = new String[] {"_id", "col1"}; Cursor allRows = myDB.query(DATABASE_TABLE, resultColumns, null, null, null, null, null, null); String res = "RESULT IS:"; Integer cindex = allRows.getColumnIndex("col1"); if (allRows.moveToFirst()) { do { res += allRows.getString(cindex)+"-"; } while (allRows.moveToNext()); } myDB.close(); Toast.makeText(getApplicationContext(), res, Toast.LENGTH_SHORT).show();}

45

Page 46: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 16: Databases

.backup ?DB? FILE Backup DB (default "main") to FILE

.bail ON|OFF Stop after hitting an error. Default OFF

.databases List names and files of attached databases

.dump ?TABLE? ... Dump the database in an SQL text format

.echo ON|OFF Turn command echo on or off

.exit Exit this program

.explain ON|OFF Turn output mode suitable for EXPLAIN on or off.

.genfkey ?OPTIONS? Options are: --no-drop: Do not drop old fkey triggers. --ignore-errors: Ignore tables with fkey errors --exec: Execute generated SQL immediately See file tool/genfkey.README in the source distribution for further information..header(s) ON|OFF Turn display of headers on or off.help Show this message.import FILE TABLE Import data from FILE into TABLE.indices TABLE Show names of all indices on TABLE.iotrace FILE Enable I/O diagnostic logging to FILE.load FILE ?ENTRY? Load an extension library.mode MODE ?TABLE? Set output mode where MODE is one of: csv Comma-separated values column Left-aligned columns. (See .width) html HTML <table> code insert SQL insert statements for TABLE line One value per line list Values delimited by .separator string tabs Tab-separated values tcl TCL list elements

.nullvalue STRING Print STRING in place of NULL values

.output FILENAME Send output to FILENAME

.output stdout Send output to the screen

.prompt MAIN CONTINUE Replace the standard prompts

.quit Exit this program

.read FILENAME Execute SQL in FILENAME

.restore ?DB? FILE Restore content of DB (default "main") from FILE

.schema ?TABLE? Show the CREATE statements

.separator STRING Change separator used by output mode and .import

.show Show the current values for various settings

.tables ?PATTERN? List names of tables matching a LIKE pattern

.timeout MS Try opening locked tables for MS milliseconds

.timer ON|OFF Turn the CPU timer measurement on or off

.width NUM NUM ... Set column widths for "column" modesqlite>

SQLite survival commands:

46

Page 47: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 16: Databases

Open/Create a Database

This is done using the command line program.

sqlite3 {database file name}

Ex:

sqlite3 my_stuff_database.db

If the database exists it will be opened, if it doesn’t exist, it will be created.

Print the database structure

.schema

Print database structure and data

.dump

Turn on column names on query results

.explain on

To turn it off do:

.explain off

Creating Tables

create table {table name} ('{column name}' {data type} primary key, '{column name}' {data type});

Ex:

CREATE TABLE my_data('id' int primary key, 'name' varchar(20), 'description' varchar(10));

SQLite command line examples: Adding a Column to a Table

alter table {table name} ADD '{column name}' {data type};

Ex:

alter table my_things ADD 'description' varchar(50);

Deleting a table

drop table {table name};

Ex:

drop table my_things;

Inserting Data into a Table

insert into {table name} values ({data}, {more data}, '{yet more data}');

Ex:

insert into my_things values (1, 'My first thing', 'It is nice');

Transactions

begin transaction;

something

commit;

Output query results to a file

.output {filename.txt}

47

Page 48: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 17: More on layoutsMost common layouts:

LinearLayout: when the order of arrangements of widgets/views of the layout needs to be horizontal or vertical manner, the LinearLayout widget comes in handy. The direction of arrangement can be set to horizontal or vertical, default being horizontal.

TableLayout : as the name suggests, this layout object is used when the layout has widgets/views that need to be arranged into rows and columns. This is similar to html tables. The cells can span columns. The TableLayout do not display its border. The columns can be made to shrink and stretch by setting the respective properties. TableRow is another helper widget which should be used in conjunction with the TableLayout.

RelativeLayout : when the position of each of the widgets/view is in relative/dependent to each other, then a relative layout is used. That is for example, when a layout is needed such that it has a text view just to the left of an Edit Textbox, and a button just below the EditText. The relation between the views are taken care in one iteration, hence if view B’s position is dependent on view A’s position, view A must come first in the layout.

FrameLayout : this is a very simply layout which is used to hold a section of the screen blank, for displaying an item or group of items at run time. All the elements added in the framelayout will be added to the top left of the screen.

AbsoluteLayout : when there is a need is to specify exact x and y co-ordinate position of the view, then AbsoluteLayout need to be used. This layout should not be used as far as possible as it is difficult to maintain.

ListView: used to display list of items in a vertically scrolling list. ListView has many optimizations that are important for large lists. ScrollView is used for vertically scrolling in which an infinite amount of space is given to the container to hold all the elements of the view. A ScrollView should have one child which has the elements to be scrolled. A ScrollView cannot be used in conjunction with a ListView since the list views optimizations will be nullified in effect.

48

Page 49: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 17: More on layoutsLinearLayout

<?xml version="1.0" encoding="utf-8"?><LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" > <TextView android:layout_width="105px" android:layout_height="wrap_content" android:text="@string/hello" /> <Button android:layout_width="100px" android:layout_height="wrap_content" android:text="Button" android:layout_gravity="right" android:layout_weight="0.2" /> <EditText android:layout_width="fill_parent" android:layout_height="wrap_content" android:textSize="18sp" android:layout_weight="0.8" /></LinearLayout>

ResultExample

49

Page 50: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 17: More on layoutsTableLayout

<?xml version="1.0" encoding="utf-8"?><TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="fill_parent" android:layout_width="fill_parent" android:background="#000044"> <TableRow> <TextView android:text="User Name:" android:width ="120px" /> <EditText android:id="@+id/txtUserName" android:width="200px" /> </TableRow> <TableRow> <TextView android:text="Password:" /> <EditText android:id="@+id/txtPassword" android:password="true" /> </TableRow> <TableRow> <TextView /> <CheckBox android:id="@+id/chkRememberPassword" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Remember Password" /> </TableRow> <TableRow> <Button android:id="@+id/buttonSignIn" android:text="Log In" /> </TableRow></TableLayout>

Result

Example

50

Page 51: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 17: More on layoutsRelativeLayout

<?xml version="1.0" encoding="utf-8"?><RelativeLayout android:id="@+id/RLayout" android:layout_width="fill_parent" android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android" > <TextView android:id="@+id/lblComments" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Comments" android:layout_alignParentTop="true" android:layout_alignParentLeft="true" /> <EditText android:id="@+id/txtComments" android:layout_width="fill_parent" android:layout_height="170px" android:textSize="18sp" android:layout_alignLeft="@+id/lblComments" android:layout_below="@+id/lblComments" android:layout_centerHorizontal="true" /> <Button android:id="@+id/btnSave" android:layout_width="125px" android:layout_height="wrap_content" android:text="Save" android:layout_below="@+id/txtComments" android:layout_alignRight="@+id/txtComments" /> <Button android:id="@+id/btnCancel" android:layout_width="124px" android:layout_height="wrap_content" android:text="Cancel" android:layout_below="@+id/txtComments" android:layout_alignLeft="@+id/txtComments" /></RelativeLayout>

Result

Example

51

Page 52: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 17: More on layoutsFrameLayout

<?xml version="1.0" encoding="utf-8"?><AbsoluteLayout android:id="@+id/widget68" android:layout_width="fill_parent" android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android" > <FrameLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_x="50px" android:layout_y="50px" > <ImageView android:src = "@drawable/logo" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </FrameLayout></AbsoluteLayout>

ResultExample

52

Page 53: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 17: More on layoutsAbsoluteLayout

<?xml version="1.0" encoding="utf-8"?><AbsoluteLayout android:id="@+id/widget68" android:layout_width="fill_parent" android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android" > <FrameLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_x="50px" android:layout_y="50px" > <ImageView android:src = "@drawable/logo" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <Button android:layout_width="100px" android:layout_height="wrap_content" android:text="Hello" /> </FrameLayout></AbsoluteLayout>

ResultExample

53

Page 54: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 17: More on layoutsScrollView

<?xml version="1.0" encoding="utf-8"?><ScrollView android:id="@+id/widget54" android:layout_width="fill_parent" android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android" > <LinearLayout android:layout_width="310px" android:layout_height="wrap_content" android:orientation="vertical"> <Button android:id="@+id/button1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Button 1"/> <Button android:id="@+id/button2" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Button 2"/> <Button android:id="@+id/button3" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Button 3"/> <EditText android:id="@+id/txt" android:layout_width="fill_parent" android:layout_height="300px"/> <Button android:id="@+id/button4" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Button 4"/> <Button android:id="@+id/button5" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Button 5"/> </LinearLayout></ScrollView>

Result

Example

SCROLL

54

Page 55: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 18: Services and background processingClass ServiceDemo:

public class ServiceDemo extends Activity { Context savedThis = this; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button startButton = (Button)findViewById(R.id.start); Button stopButton = (Button)findViewById(R.id.stop); startButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // start the service startService(new Intent(savedThis, MyService.class)); } });

stopButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // stop the service stopService(new Intent(savedThis, MyService.class)); } }); }}

55

Page 56: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 18: Services and background processingClass ServiceDemo:

import android.app.Service;import android.content.Intent;import android.media.MediaPlayer;import android.os.IBinder;import android.widget.Toast;

public class MyService extends Service { MediaPlayer player; @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { Toast.makeText(this, "MyService Created", Toast.LENGTH_SHORT).show(); player = MediaPlayer.create(this, R.raw.cendrillon); player.setLooping(false); } @Override public void onStart(Intent intent, int startid) { Toast.makeText(this, "MyService Started", Toast.LENGTH_SHORT).show(); player.start(); } @Override public void onDestroy() { player.stop(); }}

56

Page 57: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 18: Services and background processingLayout:

<?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="wrap_content" android:text="@string/hello" /> <Button android:layout_height="wrap_content" android:layout_width="fill_parent" android:id="@+id/start" android:text="Start"/>

<Button android:layout_height="wrap_content" android:layout_width="fill_parent" android:id="@+id/stop" android:text="Stop"/> </LinearLayout>

57

Page 58: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 18: Services and background processingServiceDemo manifest:

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.voxisland" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".ServiceDemo" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <service android:enabled="true" android:name=".MyService" />

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

</manifest>

58

Page 59: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 18: Services and background processingSee the services (only Android 2.0 and +):

Android 2.0 introduced a new "Running Services" activity available from the Application system settings. When brought up, it looks something like the left picture.

The main content is a list of all running services that may be of interest to the user, organized by the processes they run in. In the example here, we see three services:

• GTalkService is part of the standard Google application suit; it is running in Google's "gapps" process, which currently consumes 6.8MB. It has been started for 3 hours 55 minutes, which on this device is the time from when it was first booted.

• ActivityService is part of the Phonebook app, and its process consumes 4MB. This also has been running since boot.• SoftKeyboard is a third party input method. It has been running since I switched to it, about 4 minutes ago.

The user can tap on any of these services to control it; for normal services that are running because they were explicitly started, this will present a dialog allowing the user to explicitly stop it (right picture).

59

Page 60: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 19: Security and permissionsrequesting permissions

<uses-permission android:name="android.permission.ACCESS_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_GPS" />

examples:

<uses-permission android:name="string" />

syntax:

60

Page 61: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 19: Security and permissionsrequiring permissions

<permission android:name="com.me.app.myapp.permission.DEADLY_ACTIVITY"        android:label="@string/permlab_deadlyActivity"        android:description="@string/permdesc_deadlyActivity"        android:permissionGroup="android.permission-group.COST_MONEY"        android:protectionLevel="dangerous" />

examples:

<permission android:description="string resource"android:icon="drawable resource"android:label="string resource"android:name="string"android:permissionGroup="string"android:protectionLevel=["normal" | "dangerous" | "signature" | "signatureOrSystem"] />

syntax:

61

Page 62: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 19: Security and permissionspermissions 1/2

ACCESS_CHECKIN_PROPERTIESAllows read/write access to the "properties" table in the checkin database, to change values that get uploaded.ACCESS_COARSE_LOCATIONAllows an application to access coarse (e.g., Cell-ID, WiFi) locationACCESS_FINE_LOCATIONAllows an application to access fine (e.g., GPS) locationACCESS_LOCATION_EXTRA_COMMANDSAllows an application to access extra location provider commandsACCESS_MOCK_LOCATIONAllows an application to create mock location providers for testingACCESS_NETWORK_STATEAllows applications to access information about networksACCESS_SURFACE_FLINGERAllows an application to use SurfaceFlinger's low level featuresACCESS_WIFI_STATEAllows applications to access information about Wi-Fi networksACCOUNT_MANAGERAllows applications to call into AccountAuthenticators.AUTHENTICATE_ACCOUNTSAllows an application to act as an AccountAuthenticator for the AccountManagerBATTERY_STATSAllows an application to collect battery statisticsBIND_APPWIDGETAllows an application to tell the AppWidget service which application can access AppWidget's data.BIND_INPUT_METHODMust be required by input method services, to ensure that only the system can bind to them.BLUETOOTHAllows applications to connect to paired bluetooth devicesBLUETOOTH_ADMINAllows applications to discover and pair bluetooth devicesBRICKRequired to be able to disable the device (very dangerous!).BROADCAST_PACKAGE_REMOVEDAllows an application to broadcast a notification that an application package has been removed.

BROADCAST_SMSAllows an application to broadcast an SMS receipt notificationBROADCAST_STICKYAllows an application to broadcast sticky intents.BROADCAST_WAP_PUSHAllows an application to broadcast a WAP PUSH receipt notificationCALL_PHONEAllows an application to initiate a phone call without going through the Dialer user interface for the user to confirm the call being placed.CALL_PRIVILEGEDAllows an application to call any phone number, including emergency numbers, without going through the Dialer user interface for the user to confirm the call being placed.CAMERARequired to be able to access the camera device.CHANGE_COMPONENT_ENABLED_STATEAllows an application to change whether an application component (other than its own) is enabled or not.CHANGE_CONFIGURATIONAllows an application to modify the current configuration, such as locale.CHANGE_NETWORK_STATEAllows applications to change network connectivity stateCHANGE_WIFI_MULTICAST_STATEAllows applications to enter Wi-Fi Multicast modeCHANGE_WIFI_STATEAllows applications to change Wi-Fi connectivity stateCLEAR_APP_CACHEAllows an application to clear the caches of all installed applications on the device.CLEAR_APP_USER_DATAAllows an application to clear user dataCONTROL_LOCATION_UPDATESAllows enabling/disabling location update notifications from the radio.DELETE_CACHE_FILESAllows an application to delete cache files.DELETE_PACKAGESAllows an application to delete packages.DEVICE_POWERAllows low-level access to power management

DIAGNOSTICAllows applications to RW to diagnostic resources.DISABLE_KEYGUARDAllows applications to disable the keyguardDUMPAllows an application to retrieve state dump information from system services.EXPAND_STATUS_BARAllows an application to expand or collapse the status bar.FACTORY_TESTRun as a manufacturer test application, running as the root user.FLASHLIGHTAllows access to the flashlightFORCE_BACKAllows an application to force a BACK operation on whatever is the top activity.GET_ACCOUNTSAllows access to the list of accounts in the Accounts ServiceGET_PACKAGE_SIZEAllows an application to find out the space used by any package.GET_TASKSAllows an application to get information about the currently or recently running tasks: a thumbnail representation of the tasks, what activities are running in it, etc.GLOBAL_SEARCHThis permission can be used on content providers to allow the global search system to access their data.HARDWARE_TESTAllows access to hardware peripherals.INJECT_EVENTSAllows an application to inject user events (keys, touch, trackball) into the event stream and deliver them to ANY window.INSTALL_LOCATION_PROVIDERAllows an application to install a location provider into the Location ManagerINSTALL_PACKAGESAllows an application to install packages.INTERNAL_SYSTEM_WINDOWAllows an application to open windows that are for use by parts of the system user interface.

62

Page 63: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 19: Security and permissionspermissions 2/2

INTERNETAllows applications to open network sockets.MANAGE_ACCOUNTSAllows an application to manage the list of accounts in the AccountManagerMANAGE_APP_TOKENSAllows an application to manage (create, destroy, Z-order) application tokens in the window manager.MODIFY_AUDIO_SETTINGSAllows an application to modify global audio settingsMODIFY_PHONE_STATEAllows modification of the telephony state - power on, mmi, etc.MOUNT_FORMAT_FILESYSTEMSAllows formatting file systems for removable storage.MOUNT_UNMOUNT_FILESYSTEMSAllows mounting and unmounting file systems for removable storage.PERSISTENT_ACTIVITYAllow an application to make its activities persistent.PROCESS_OUTGOING_CALLSAllows an application to monitor, modify, or abort outgoing calls.READ_CALENDARAllows an application to read the user's calendar data.READ_CONTACTSAllows an application to read the user's contacts data.READ_FRAME_BUFFERAllows an application to take screen shots and more generally get access to the frame buffer dataREAD_HISTORY_BOOKMARKSAllows an application to read (but not write) the user's browsing history and bookmarks.READ_INPUT_STATEAllows an application to retrieve the current state of keys and switches.READ_LOGSAllows an application to read the low-level system log files.READ_OWNER_DATAAllows an application to read the owner's data.READ_PHONE_STATEAllows read only access to phone state.READ_SMSAllows an application to read SMS messages.

READ_SYNC_STATSAllows applications to read the sync statsREBOOTRequired to be able to reboot the device.RECEIVE_BOOT_COMPLETEDAllows an application to receive the ACTION_BOOT_COMPLETED that is broadcast after the system finishes booting.RECEIVE_MMSAllows an application to monitor incoming MMS messages, to record or perform processing on them.RECEIVE_SMSAllows an application to monitor incoming SMS messages, to record or perform processing on them.RECEIVE_WAP_PUSHAllows an application to monitor incoming WAP push messages.RECORD_AUDIOAllows an application to record audioREORDER_TASKSAllows an application to change the Z-order of tasksRESTART_PACKAGESAllows an application to restart other applications.SEND_SMSAllows an application to send SMS messages.SET_ACTIVITY_WATCHERAllows an application to watch and control how activities are started globally in the system.SET_ALWAYS_FINISHAllows an application to control whether activities are immediately finished when put in the background.SET_ANIMATION_SCALEModify the global animation scaling factor.SET_DEBUG_APPConfigure an application for debugging.SET_ORIENTATIONAllows low-level access to setting the orientation (actually rotation) of the screen.SET_PREFERRED_APPLICATIONSThis constant is deprecated. No longer useful, see addPackageToPreferred(String) for details.SET_PROCESS_LIMITAllows an application to set the maximum number of (not needed) application processes that can be running.

SET_PROCESS_LIMITAllows an application to set the maximum number of (not needed) application processes that can be running.SET_TIME_ZONEAllows applications to set the system time zoneSET_WALLPAPERAllows applications to set the wallpaperSTATUS_BARAllows an application to open, close, or disable the status bar and its icons.SUBSCRIBED_FEEDS_READAllows an application to allow access the subscribed feeds ContentProvider.UPDATE_DEVICE_STATSAllows an application to update device statistics.USE_CREDENTIALSAllows an application to request authtokens from the AccountManagerVIBRATEAllows access to the vibratorWAKE_LOCKAllows using PowerManager WakeLocks to keep processor from sleeping or screen from dimmingWRITE_APN_SETTINGSAllows applications to write the apn settingsWRITE_CALENDARAllows an application to write (but not read) the user's calendar data.WRITE_CONTACTSAllows an application to write (but not read) the user's contacts data.WRITE_EXTERNAL_STORAGEAllows an application to write to external storageWRITE_GSERVICESAllows an application to modify the Google service map.WRITE_HISTORY_BOOKMARKSAllows an application to write (but not read) the user's browsing history and bookmarks.WRITE_OWNER_DATAAllows an application to write (but not read) the owner's data.WRITE_SECURE_SETTINGSAllows an application to read or write the secure system settings.WRITE_SETTINGSAllows an application to read or write the system settings.WRITE_SMSAllows an application to write SMS messages.WRITE_SYNC_SETTINGSAllows applications to write the sync settings

63

Page 64: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 20: Debuggingsuffer function:

public void suffer() { for (int i=0; i<1000; i++) { for (int j=0; j<1000; j++) { int k = i*j; } } }

64

Page 65: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 20: DebuggingTraceview result:

65

Page 66: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 21: Publish an application

1. Test

2. Setup an Icon

3. Add a license

4. Clean-up your code

5. Version your application

6. Create a certificate

7. Export for release

8. Sign

9. Retest

10. Publish

66

Page 67: Curso de Android - VoxIsland

http://android.voxisland.com - (c) VoxIsland 2010

Chapter 21: Publish an application

2. Setup an Icon:

Check the Icon Design Guidelines at http://developer.android.com/guide/practices/ui_guidelines/icon_design.html

6. Create a certificate

keytool -genkey -v -keystore com.voxisland -alias jaykey -keyalg RSA -validity 10000

8. Sign the application

jarsigner -verbose -keystore com.voxisland simplelist.apk jaykey

Optimize

zipalign -v 4 simplelist.apk simplelist2.apk

67