Curso de android vox island

  • 231 views
Uploaded on

 

More in: Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
    Be the first to like this
No Downloads

Views

Total Views
231
On Slideshare
0
From Embeds
0
Number of Embeds
0

Actions

Shares
Downloads
1
Comments
0
Likes
0

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. Training companion ANDROID TUTORIAL http://android.voxisland.com (c) 2010 VoxIsland 1
  • 2. Chapter 2: Getting to know Android History In July 2005, Google acquired Android, Inc., a small startup company based in Palo Alto, California, USA. Android's cofounders 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 http://android.voxisland.com - (c) VoxIsland 2010 2
  • 3. Chapter 2: Getting to know Android The Open Handset Alliance Mobile Operators Software Companies Commercialization Companies Semiconductors Companies Handset Manufacturers China Mobile KDDI Corporation NTT DoCoMo Sprint Nextel T-Mobile Telecom Italia Telefonica Ascender Corporation eBay Esmertec Google LivingImage Myriad Group|Myriad NMS Communications Nuance Communications PacketVideo SkyPop SONiVOX Aplix Noser Engineering The Astonishing Tribe Wind River Systems Audience Broadcom Corporation Intel Corporation Marvell Technology Group Nvidia Corporation Qualcomm SiRF|SiRF Technology Holdings Synaptics Texas Instruments High Tech Computer Corporation|HTC LG Motorola Samsung Electronics Vodafone Softbank China Unicom SVox Borqs Omron SW Teleca Sasken Comm Tech Ltd ASUSTek Garmin Huawei Tech Sony Ericsson Toshiba Acer Borqs Omron SW Teleca Sasken Comm Tech Ltd founding members in bold as of 03-2010 http://android.voxisland.com - (c) VoxIsland 2010 3
  • 4. Chapter 2: Getting to know Android Android application development VS traductionnal development Power no need to address limiting power consumption is crucial big display small display CPU Ghz hunders of Mhz Memory Gb Mb Storage Tb or Gb Gb or Mb LIMITATIONS 2. Re-Usability of components (mashups) will speed-up developments 3. Interchangeable apps will speed-up developments Computer Screen 1. Limited resources will slow-down developments Android phone http://android.voxisland.com - (c) VoxIsland 2010 4
  • 5. 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 http://android.voxisland.com - (c) VoxIsland 2010 5
  • 6. Chapter 3: Android development setup Adding 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 http://android.voxisland.com - (c) VoxIsland 2010 6
  • 7. 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); } } http://android.voxisland.com - (c) VoxIsland 2010 7
  • 8. Chapter 4: Android development with Eclipse JAVA perspective: http://android.voxisland.com - (c) VoxIsland 2010 8
  • 9. Chapter 4: Android development with Eclipse DDMS perspective: http://android.voxisland.com - (c) VoxIsland 2010 9
  • 10. Chapter 4: Android development with Eclipse DEBUG perspective: http://android.voxisland.com - (c) VoxIsland 2010 10
  • 11. Chapter 5: Hello Android project structure R.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; } } http://android.voxisland.com - (c) VoxIsland 2010 11
  • 12. Chapter 5: Hello Android project structure AndroidManifest.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> http://android.voxisland.com - (c) VoxIsland 2010 12
  • 13. Chapter 5: Hello Android project structure main.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> http://android.voxisland.com - (c) VoxIsland 2010 13
  • 14. 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> http://android.voxisland.com - (c) VoxIsland 2010 14
  • 15. Chapter 5: Hello Android project structure AndroidManifest.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> http://android.voxisland.com - (c) VoxIsland 2010 15
  • 16. Chapter 6,7,8: The Joshua Project The project once completed: http://android.voxisland.com - (c) VoxIsland 2010 16
  • 17. Layout: A B C <?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" > D E <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"/> Chapter 6,7,8: The Joshua Project F <LinearLayout android:layout_width="fill_parent" android:layout_height="20px" android:orientation="horizontal"> G H I <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> J <RadioGroup android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/myRadioGroup" android:orientation="horizontal"> K <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"/> L M </RadioGroup> </LinearLayout> </LinearLayout> http://android.voxisland.com - (c) VoxIsland 2010 17
  • 18. Chapter 6,7,8: The Joshua Project Layout: B D E G H I C F K L M J A http://android.voxisland.com - (c) VoxIsland 2010 18
  • 19. Joshua class: package com.voxisland; import import import import import import import import import import android.app.Activity; android.graphics.Color; android.os.Bundle; android.view.View; android.view.View.OnClickListener; android.widget.Button; android.widget.CheckBox; android.widget.RadioButton; android.widget.TextView; 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); Chapter 6,7,8: The Joshua Project 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); } } http://android.voxisland.com - (c) VoxIsland 2010 19
  • 20. SimpleList class (1/2): Chapter 9: Lists package com.voxisland; import java.util.ArrayList; import java.util.Arrays; import import import import import import import import import android.app.AlertDialog; android.app.ListActivity; android.content.Context; android.content.DialogInterface; android.os.Bundle; android.view.View; android.widget.AdapterView; android.widget.ArrayAdapter; 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; http://android.voxisland.com - (c) VoxIsland 2010 20
  • 21. Chapter 9: Lists SimpleList 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); } } http://android.voxisland.com - (c) VoxIsland 2010 21
  • 22. Chapter 10: Lists ArrayAdapter: 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 Methods void 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 T 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. getFilter() Returns a filter that can be used to constrain data with a filtering pattern. getItem(int position) long getItemId(int position) int getPosition(T item) Returns the position of the specified item in the array. getView(int position, View convertView, ViewGroup parent) Filter View void void void void void void insert(T object, int index) Inserts the specified object at the specified index in the array. notifyDataSetChanged() Notifies the attached View that the underlying data has been changed and it should refresh itself. remove(T object) Removes the specified object from the array. setDropDownViewResource(int resource) Sets the layout resource to create the drop down views. setNotifyOnChange(boolean notifyOnChange) Control whether methods that change the list (add(T), insert(T, int), remove(T), clear()) automatically call notifyDataSetChanged(). sort(Comparator<? super T> comparator) Sorts the content of this adapter using the specified comparator. http://android.voxisland.com - (c) VoxIsland 2010 22
  • 23. Chapter 10: Long clicks Definition: 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); http://android.voxisland.com - (c) VoxIsland 2010 23
  • 24. Chapter 11: Dialog boxes Adding a dialog box to the list example: @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; http://android.voxisland.com - (c) VoxIsland 2010 24
  • 25. Chapter 11: Dialog boxes Adding a dialog box to the list example: @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; http://android.voxisland.com - (c) VoxIsland 2010 25
  • 26. AlertDialog builder 1/3: Chapter 11: Dialog boxes Public Methods AlertDialog 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. http://android.voxisland.com - (c) VoxIsland 2010 26
  • 27. AlertDialog builder 2/3: 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. http://android.voxisland.com - (c) VoxIsland 2010 27
  • 28. AlertDialog builder 3/3: 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. http://android.voxisland.com - (c) VoxIsland 2010 28
  • 29. Intents1 class 1/2: Chapter 12: Intents 1 package com.voxisland; import import import import import android.app.Activity; android.content.Intent; android.os.Bundle; android.view.View; 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); } }); http://android.voxisland.com - (c) VoxIsland 2010 29
  • 30. Intents1 class 2/2: Chapter 12: Intents 1 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); } }); } } http://android.voxisland.com - (c) VoxIsland 2010 30
  • 31. Activity1 class: Chapter 13: Intents 2 package com.voxisland; import import import import import android.app.Activity; android.content.Intent; android.os.Bundle; android.view.View; 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); } } } http://android.voxisland.com - (c) VoxIsland 2010 31
  • 32. Chapter 13: Intents 2 Activity2 class: package com.voxisland; import import import import import android.app.Activity; android.content.Intent; android.os.Bundle; android.view.View; 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(); } } } http://android.voxisland.com - (c) VoxIsland 2010 32
  • 33. Chapter 13: Intents 2 Standard actions: ACTION_MAIN ACTION_VIEW ACTION_ATTACH_DATA ACTION_EDIT ACTION_PICK ACTION_CHOOSER ACTION_GET_CONTENT ACTION_DIAL ACTION_CALL ACTION_SEND ACTION_SENDTO ACTION_ANSWER ACTION_INSERT ACTION_DELETE ACTION_RUN ACTION_SYNC ACTION_PICK_ACTIVITY ACTION_SEARCH ACTION_WEB_SEARCH ACTION_FACTORY_TEST http://android.voxisland.com - (c) VoxIsland 2010 33
  • 34. Chapter 13: Intents 2 Standard boradcast actions: ACTION_TIME_TICK ACTION_TIME_CHANGED ACTION_TIMEZONE_CHANGED ACTION_BOOT_COMPLETED ACTION_PACKAGE_ADDED ACTION_PACKAGE_CHANGED ACTION_PACKAGE_REMOVED ACTION_PACKAGE_RESTARTED ACTION_PACKAGE_DATA_CLEARED ACTION_UID_REMOVED ACTION_BATTERY_CHANGED ACTION_POWER_CONNECTED ACTION_POWER_DISCONNECTED ACTION_SHUTDOWN http://android.voxisland.com - (c) VoxIsland 2010 34
  • 35. Chapter 13: Intents 2 Standard boradcast actions: ACTION_TIME_TICK ACTION_TIME_CHANGED ACTION_TIMEZONE_CHANGED ACTION_BOOT_COMPLETED ACTION_PACKAGE_ADDED ACTION_PACKAGE_CHANGED ACTION_PACKAGE_REMOVED ACTION_PACKAGE_RESTARTED ACTION_PACKAGE_DATA_CLEARED ACTION_UID_REMOVED ACTION_BATTERY_CHANGED ACTION_POWER_CONNECTED ACTION_POWER_DISCONNECTED ACTION_SHUTDOWN http://android.voxisland.com - (c) VoxIsland 2010 35
  • 36. Chapter 13: Intents 2 Standard categories: CATEGORY_DEFAULT CATEGORY_BROWSABLE CATEGORY_TAB CATEGORY_ALTERNATIVE CATEGORY_SELECTED_ALTERNATIVE CATEGORY_LAUNCHER CATEGORY_INFO CATEGORY_HOME CATEGORY_PREFERENCE CATEGORY_TEST CATEGORY_CAR_DOCK CATEGORY_DESK_DOCK http://android.voxisland.com - (c) VoxIsland 2010 36
  • 37. Chapter 13: Intents 2 Standard extra data: EXTRA_ALARM_COUNT EXTRA_BCC EXTRA_CC EXTRA_CHANGED_COMPONENT_NAME EXTRA_DATA_REMOVED EXTRA_DOCK_STATE EXTRA_DOCK_STATE_CAR EXTRA_DOCK_STATE_DESK EXTRA_DOCK_STATE_UNDOCKED EXTRA_DONT_KILL_APP EXTRA_EMAIL EXTRA_INITIAL_INTENTS EXTRA_INTENT EXTRA_KEY_EVENT EXTRA_PHONE_NUMBER EXTRA_REMOTE_INTENT_TOKEN EXTRA_REPLACING EXTRA_SHORTCUT_ICON EXTRA_SHORTCUT_ICON_RESOURCE EXTRA_SHORTCUT_INTENT EXTRA_STREAM EXTRA_SHORTCUT_NAME EXTRA_SUBJECT EXTRA_TEMPLATE EXTRA_TEXT EXTRA_TITLE EXTRA_UID http://android.voxisland.com - (c) VoxIsland 2010 37
  • 38. Chapter 14: Option and Context menus package com.voxisland; import import import import import Options Menu android.app.Activity; android.os.Bundle; android.view.Menu; android.view.MenuItem; 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; } } http://android.voxisland.com - (c) VoxIsland 2010 38
  • 39. Chapter 14: Option and Context menus package com.voxisland; import import import import import import import import import android.app.Activity; android.os.Bundle; android.view.ContextMenu; android.view.Menu; android.view.MenuItem; android.view.View; android.view.ContextMenu.ContextMenuInfo; android.widget.TextView; android.widget.Toast; Context Menu 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; } } http://android.voxisland.com - (c) VoxIsland 2010 39
  • 40. 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. http://android.voxisland.com - (c) VoxIsland 2010 40
  • 41. Chapter 16: Databases package com.voxisland; import import import import import import import import import import android.app.Activity; android.content.ContentValues; android.content.Context; android.database.Cursor; android.database.sqlite.SQLiteDatabase; android.os.Bundle; android.view.View; android.view.View.OnClickListener; android.widget.Button; 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 Button Button Button butCreate butAdd butCount butShow = = = = (Button)findViewById(R.id.myButCreate); (Button)findViewById(R.id.myButAdd); (Button)findViewById(R.id.myButCount); (Button)findViewById(R.id.myButShow); // MORE HERE } } http://android.voxisland.com - (c) VoxIsland 2010 41
  • 42. Chapter 16: Databases @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button Button Button Button butCreate butAdd butCount butShow = = = = (Button)findViewById(R.id.myButCreate); (Button)findViewById(R.id.myButAdd); (Button)findViewById(R.id.myButCount); (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(); } }); http://android.voxisland.com - (c) VoxIsland 2010 42
  • 43. 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(); } http://android.voxisland.com - (c) VoxIsland 2010 43
  • 44. 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(); } http://android.voxisland.com - (c) VoxIsland 2010 44
  • 45. 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(); http://android.voxisland.com - (c) VoxIsland 2010 45
  • 46. Chapter 16: Databases SQLite survival commands: .backup ?DB? FILE .bail ON|OFF .databases .dump ?TABLE? ... .echo ON|OFF .exit .explain ON|OFF .genfkey ?OPTIONS? .header(s) ON|OFF .help .import FILE TABLE .indices TABLE .iotrace FILE .load FILE ?ENTRY? .mode MODE ?TABLE? Backup DB (default "main") to FILE Stop after hitting an error. Default OFF List names and files of attached databases Dump the database in an SQL text format Turn command echo on or off Exit this program Turn output mode suitable for EXPLAIN on or off. 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. Turn display of headers on or off Show this message Import data from FILE into TABLE Show names of all indices on TABLE Enable I/O diagnostic logging to FILE Load an extension library 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 .output FILENAME .output stdout .prompt MAIN CONTINUE .quit .read FILENAME .restore ?DB? FILE .schema ?TABLE? .separator STRING .show .tables ?PATTERN? .timeout MS .timer ON|OFF .width NUM NUM ... sqlite> Print STRING in place of NULL values Send output to FILENAME Send output to the screen Replace the standard prompts Exit this program Execute SQL in FILENAME Restore content of DB (default "main") from FILE Show the CREATE statements Change separator used by output mode and .import Show the current values for various settings List names of tables matching a LIKE pattern Try opening locked tables for MS milliseconds Turn the CPU timer measurement on or off Set column widths for "column" mode http://android.voxisland.com - (c) VoxIsland 2010 46
  • 47. Chapter 16: Databases SQLite command line examples: Adding a Column to a Table Open/Create a Database alter table {table name} ADD '{column name}' {data type}; This is done using the command line program. Ex: sqlite3 {database file name} alter table my_things ADD 'description' varchar(50); Ex: Deleting a table sqlite3 my_stuff_database.db drop table {table name}; If the database exists it will be opened, if it doesn’t exist, it will be created. Ex: Print the database structure drop table my_things; .schema Inserting Data into a Table Print database structure and data insert into {table name} values ({data}, {more data}, '{yet more data}'); .dump Ex: Turn on column names on query results .explain on insert into my_things values (1, 'My first thing', 'It is nice'); To turn it off do: Transactions .explain off begin transaction; Creating Tables something create table {table name} ('{column name}' primary key, '{column name}' {data type}); {data type} commit; Output query results to a file Ex: CREATE TABLE my_data('id' int primary key, 'name' varchar (20), 'description' varchar(10)); .output {filename.txt} http://android.voxisland.com - (c) VoxIsland 2010 47
  • 48. Chapter 17: More on layouts Most 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. http://android.voxisland.com - (c) VoxIsland 2010 48
  • 49. Chapter 17: More on layouts LinearLayout Example Result <?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> http://android.voxisland.com - (c) VoxIsland 2010 49
  • 50. TableLayout Chapter 17: More on layouts Example <?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 http://android.voxisland.com - (c) VoxIsland 2010 50
  • 51. RelativeLayout Chapter 17: More on layouts Example <?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 http://android.voxisland.com - (c) VoxIsland 2010 51
  • 52. FrameLayout Chapter 17: More on layouts <?xml version="1.0" encoding="utf-8"?> Example <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> Result http://android.voxisland.com - (c) VoxIsland 2010 52
  • 53. AbsoluteLayout Chapter 17: More on layouts <?xml version="1.0" encoding="utf-8"?> Example <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> Result http://android.voxisland.com - (c) VoxIsland 2010 53
  • 54. ScrollView Chapter 17: More on layouts <?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> Example Result SCROLL http://android.voxisland.com - (c) VoxIsland 2010 54
  • 55. Chapter 18: Services and background processing Class 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)); } }); } } http://android.voxisland.com - (c) VoxIsland 2010 55
  • 56. Chapter 18: Services and background processing Class ServiceDemo: import import import import import android.app.Service; android.content.Intent; android.media.MediaPlayer; android.os.IBinder; 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(); } } http://android.voxisland.com - (c) VoxIsland 2010 56
  • 57. Chapter 18: Services and background processing 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: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> http://android.voxisland.com - (c) VoxIsland 2010 57
  • 58. Chapter 18: Services and background processing ServiceDemo 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> http://android.voxisland.com - (c) VoxIsland 2010 58
  • 59. Chapter 18: Services and background processing See 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). http://android.voxisland.com - (c) VoxIsland 2010 59
  • 60. Chapter 19: Security and permissions requesting permissions syntax: <uses-permission android:name="string" /> examples: <uses-permission android:name="android.permission.ACCESS_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_GPS" /> http://android.voxisland.com - (c) VoxIsland 2010 60
  • 61. Chapter 19: Security and permissions requiring permissions syntax: <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"] /> examples: <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" /> http://android.voxisland.com - (c) VoxIsland 2010 61
  • 62. permissions 1/2 Chapter 19: Security and permissions ACCESS_CHECKIN_PROPERTIES Allows read/write access to the "properties" table in the checkin database, to change values that get uploaded. ACCESS_COARSE_LOCATION Allows an application to access coarse (e.g., Cell-ID, WiFi) location ACCESS_FINE_LOCATION Allows an application to access fine (e.g., GPS) location ACCESS_LOCATION_EXTRA_COMMANDS Allows an application to access extra location provider commands ACCESS_MOCK_LOCATION Allows an application to create mock location providers for testing ACCESS_NETWORK_STATE Allows applications to access information about networks ACCESS_SURFACE_FLINGER Allows an application to use SurfaceFlinger's low level features ACCESS_WIFI_STATE Allows applications to access information about Wi-Fi networks ACCOUNT_MANAGER Allows applications to call into AccountAuthenticators. AUTHENTICATE_ACCOUNTS Allows an application to act as an AccountAuthenticator for the AccountManager BATTERY_STATS Allows an application to collect battery statistics BIND_APPWIDGET Allows an application to tell the AppWidget service which application can access AppWidget's data. BIND_INPUT_METHOD Must be required by input method services, to ensure that only the system can bind to them. BLUETOOTH Allows applications to connect to paired bluetooth devices BLUETOOTH_ADMIN Allows applications to discover and pair bluetooth devices BRICK Required to be able to disable the device (very dangerous!). BROADCAST_PACKAGE_REMOVED Allows an application to broadcast a notification that an application package has been removed. BROADCAST_SMS Allows an application to broadcast an SMS receipt notification BROADCAST_STICKY Allows an application to broadcast sticky intents. BROADCAST_WAP_PUSH Allows an application to broadcast a WAP PUSH receipt notification CALL_PHONE Allows an application to initiate a phone call without going through the Dialer user interface for the user to confirm the call being placed. CALL_PRIVILEGED Allows 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. CAMERA Required to be able to access the camera device. CHANGE_COMPONENT_ENABLED_STATE Allows an application to change whether an application component (other than its own) is enabled or not. CHANGE_CONFIGURATION Allows an application to modify the current configuration, such as locale. CHANGE_NETWORK_STATE Allows applications to change network connectivity state CHANGE_WIFI_MULTICAST_STATE Allows applications to enter Wi-Fi Multicast mode CHANGE_WIFI_STATE Allows applications to change Wi-Fi connectivity state CLEAR_APP_CACHE Allows an application to clear the caches of all installed applications on the device. CLEAR_APP_USER_DATA Allows an application to clear user data CONTROL_LOCATION_UPDATES Allows enabling/disabling location update notifications from the radio. DELETE_CACHE_FILES Allows an application to delete cache files. DELETE_PACKAGES Allows an application to delete packages. DEVICE_POWER Allows low-level access to power management DIAGNOSTIC Allows applications to RW to diagnostic resources. DISABLE_KEYGUARD Allows applications to disable the keyguard DUMP Allows an application to retrieve state dump information from system services. EXPAND_STATUS_BAR Allows an application to expand or collapse the status bar. FACTORY_TEST Run as a manufacturer test application, running as the root user. FLASHLIGHT Allows access to the flashlight FORCE_BACK Allows an application to force a BACK operation on whatever is the top activity. GET_ACCOUNTS Allows access to the list of accounts in the Accounts Service GET_PACKAGE_SIZE Allows an application to find out the space used by any package. GET_TASKS Allows 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_SEARCH This permission can be used on content providers to allow the global search system to access their data. HARDWARE_TEST Allows access to hardware peripherals. INJECT_EVENTS Allows an application to inject user events (keys, touch, trackball) into the event stream and deliver them to ANY window. INSTALL_LOCATION_PROVIDER Allows an application to install a location provider into the Location Manager INSTALL_PACKAGES Allows an application to install packages. INTERNAL_SYSTEM_WINDOW Allows an application to open windows that are for use by parts of the system user interface. http://android.voxisland.com - (c) VoxIsland 2010 62
  • 63. permissions 2/2 Chapter 19: Security and permissions INTERNET Allows applications to open network sockets. MANAGE_ACCOUNTS Allows an application to manage the list of accounts in the AccountManager MANAGE_APP_TOKENS Allows an application to manage (create, destroy, Z-order) application tokens in the window manager. MODIFY_AUDIO_SETTINGS Allows an application to modify global audio settings MODIFY_PHONE_STATE Allows modification of the telephony state - power on, mmi, etc. MOUNT_FORMAT_FILESYSTEMS Allows formatting file systems for removable storage. MOUNT_UNMOUNT_FILESYSTEMS Allows mounting and unmounting file systems for removable storage. PERSISTENT_ACTIVITY Allow an application to make its activities persistent. PROCESS_OUTGOING_CALLS Allows an application to monitor, modify, or abort outgoing calls. READ_CALENDAR Allows an application to read the user's calendar data. READ_CONTACTS Allows an application to read the user's contacts data. READ_FRAME_BUFFER Allows an application to take screen shots and more generally get access to the frame buffer data READ_HISTORY_BOOKMARKS Allows an application to read (but not write) the user's browsing history and bookmarks. READ_INPUT_STATE Allows an application to retrieve the current state of keys and switches. READ_LOGS Allows an application to read the low-level system log files. READ_OWNER_DATA Allows an application to read the owner's data. READ_PHONE_STATE Allows read only access to phone state. READ_SMS Allows an application to read SMS messages. READ_SYNC_STATS Allows applications to read the sync stats REBOOT Required to be able to reboot the device. RECEIVE_BOOT_COMPLETED Allows an application to receive the ACTION_BOOT_COMPLETED that is broadcast after the system finishes booting. RECEIVE_MMS Allows an application to monitor incoming MMS messages, to record or perform processing on them. RECEIVE_SMS Allows an application to monitor incoming SMS messages, to record or perform processing on them. RECEIVE_WAP_PUSH Allows an application to monitor incoming WAP push messages. RECORD_AUDIO Allows an application to record audio REORDER_TASKS Allows an application to change the Z-order of tasks RESTART_PACKAGES Allows an application to restart other applications. SEND_SMS Allows an application to send SMS messages. SET_ACTIVITY_WATCHER Allows an application to watch and control how activities are started globally in the system. SET_ALWAYS_FINISH Allows an application to control whether activities are immediately finished when put in the background. SET_ANIMATION_SCALE Modify the global animation scaling factor. SET_DEBUG_APP Configure an application for debugging. SET_ORIENTATION Allows low-level access to setting the orientation (actually rotation) of the screen. SET_PREFERRED_APPLICATIONS This constant is deprecated. No longer useful, see addPackageToPreferred(String) for details. SET_PROCESS_LIMIT Allows an application to set the maximum number of (not needed) application processes that can be running. SET_PROCESS_LIMIT Allows an application to set the maximum number of (not needed) application processes that can be running. SET_TIME_ZONE Allows applications to set the system time zone SET_WALLPAPER Allows applications to set the wallpaper STATUS_BAR Allows an application to open, close, or disable the status bar and its icons. SUBSCRIBED_FEEDS_READ Allows an application to allow access the subscribed feeds ContentProvider. UPDATE_DEVICE_STATS Allows an application to update device statistics. USE_CREDENTIALS Allows an application to request authtokens from the AccountManager VIBRATE Allows access to the vibrator WAKE_LOCK Allows using PowerManager WakeLocks to keep processor from sleeping or screen from dimming WRITE_APN_SETTINGS Allows applications to write the apn settings WRITE_CALENDAR Allows an application to write (but not read) the user's calendar data. WRITE_CONTACTS Allows an application to write (but not read) the user's contacts data. WRITE_EXTERNAL_STORAGE Allows an application to write to external storage WRITE_GSERVICES Allows an application to modify the Google service map. WRITE_HISTORY_BOOKMARKS Allows an application to write (but not read) the user's browsing history and bookmarks. WRITE_OWNER_DATA Allows an application to write (but not read) the owner's data. WRITE_SECURE_SETTINGS Allows an application to read or write the secure system settings. WRITE_SETTINGS Allows an application to read or write the system settings. WRITE_SMS Allows an application to write SMS messages. WRITE_SYNC_SETTINGS Allows applications to write the sync settings http://android.voxisland.com - (c) VoxIsland 2010 63
  • 64. Chapter 20: Debugging suffer function: public void suffer() { for (int i=0; i<1000; i++) { for (int j=0; j<1000; j++) { int k = i*j; } } } http://android.voxisland.com - (c) VoxIsland 2010 64
  • 65. Traceview result: Chapter 20: Debugging http://android.voxisland.com - (c) VoxIsland 2010 65
  • 66. 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 http://android.voxisland.com - (c) VoxIsland 2010 66
  • 67. 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 http://android.voxisland.com - (c) VoxIsland 2010 67