android basic tutorial

55
ANDROID Android is open source device independent Mobile operating system Developed by Andy Rubbin in the Year 2005, Present Android Manager at Google Picheai Google Introduced OHA (Open Handset Alliances) combination of Different Platform companies Android Categories 4 and 17 Versions up to 2012 1X – Only for Mobile Phones 2X– Only for Mobile Phones 3X– Only for Tablet PCs 4X – For both Mobile and Tablet PCs Software Requirements for Android Android SDK, Core Java, Android XML, Eclipse IDE Android Architecture Android Operating System Android Application Android Application Framework (Android API Google API and Java API) Native Libraries Execution Area (DVM) Linux Kernel Application Development Components Resources (Images, Audio/Video files, Text files …etc.): Before design any android application it is highly recommended to add the resources like audio/video files, text files…Etc. Layout Files: Layout are the GUI screens in Android Applications, which will gives Provisioning to the end user either to provide input values or to check the output. Activity Classes: java code to perform the operation (Business Logic) Manifest File: This is the Starting Executable file by the DVM, in this all the activity files should registered and it decides the First Executable file. Android Project Directory Structure src: Contains the Java packages the developer writes or imports for the application. Each package can have multiple .java files representing different classes. res/ layout: Contains XML files that contains the layout of each screen. res/values: Contains XML Files used as reference by other files (strings, dimensions, colors…etc.) res/raw: Contains Audio/Video files Page | 1

Upload: smartmonk

Post on 15-Jan-2015

325 views

Category:

Mobile


5 download

DESCRIPTION

Tutorial for android learners

TRANSCRIPT

Page 1: Android Basic Tutorial

ANDROIDAndroid is open source device independent Mobile operating system Developed by Andy Rubbin in the Year 2005, Present Android Manager at Google PicheaiGoogle Introduced OHA (Open Handset Alliances) combination of Different Platform companies

Android Categories 4 and 17 Versions up to 2012 1X – Only for Mobile Phones2X– Only for Mobile Phones3X– Only for Tablet PCs4X – For both Mobile and Tablet PCs

Software Requirements for Android Android SDK, Core Java, Android XML, Eclipse IDE

Android ArchitectureAndroid Operating System

Android ApplicationAndroid Application Framework (Android API Google API and Java API)

Native Libraries Execution Area (DVM)Linux Kernel

Application Development Components Resources (Images, Audio/Video files, Text files …etc.): Before design any android application it is highly recommended to add the resources like audio/video files, text files…Etc.Layout Files: Layout are the GUI screens in Android Applications, which will gives Provisioning to the end user either to provide input values or to check the output. Activity Classes: java code to perform the operation (Business Logic) Manifest File: This is the Starting Executable file by the DVM, in this all the activity files should registered and it decides the First Executable file.

Android Project Directory Structure src: Contains the Java packages the developer writes or imports for the application. Each package can have multiple .java files representing different classes.res/ layout: Contains XML files that contains the layout of each screen. res/values: Contains XML Files used as reference by other files (strings, dimensions, colors…etc.)res/raw: Contains Audio/Video filesres/menu: Contain Menu items res/drawable-hdpi/mdpi…: Contains density wise pixel images which are used for application. assets: Contains Additional non media files the application usesgen: Contains auto generated code, including the generated class R.java.Android Mainfest.xml: Specifies the project to the Android OS.

P a g e | 1

Page 2: Android Basic Tutorial

Execution Flow of Android Application

P a g e | 2

Auto Generated .Java file for resource registration

AAP Tool

APIAndroid

JAVA

Google

Android OS and DVM (Emulator of Mobile)

.apk Files

APK Builder

.dex Files

DX Tool

R.ClassAct3.class

Act2.class

Act1.class

JVM

R.javaAct3.java

Act2.java

Act1.java

Layout Files

Text FilesImagesAudio/Video ………………………etc.Manifest File

.apk compressed Android application file (Executable file in Dalvik Virtual Machine)

Used to Compress the AAPT package and .dex files

Java Compiler Converts .java Files into .class files

DX Tool will convert the all .class files in to .dex files (Dalvik Executable Files)

Android assets Packaging tools (AAPT) will compress the Manifest, Resource Resources, Layout files into common

FilesTools

Page 3: Android Basic Tutorial

SYNTAXES1. Activity Class:

Class <class name> extends Activity{@Override public void onCreate(Bundle saveInstantState){Super.onCreate(saveInstantState);setContentView(R.Layout.XMLFileName);:::::::::::::: //Business Logic::::::::::::::

:::::::::::::: //Business Logic perform some operation ::::::::::::::

}* saveInstantState or any objref

2. Programmatically Registrations

EditText e1 =(EditText)findViewById(R.id.EditText1);String s1=e1.getTest().toString();

Button b1 = (Button)findViewById(R.id.Button1);b1.onClickListener(this);

ImageView v1=(ImageView)findViewById(R.id.image);v1.setImageResource(r.drawable.myimage);

3. Normal Switching Intent objref=new Intent(SourceActivity context, DestinationActivityclassname.class);startActivity(objref);

ExampleIntent i=new Intent(this,Act2.class);startActivity(i);

4. Switching with dataAct1.javapublic void onCreate(Bundle saveInstantState){Super.onCreate(saveInstantState);setContentView(R.Layout.XMLFileName);:::::::::::::: //Business Logic}

P a g e | 3

Page 4: Android Basic Tutorial

public void onClick(View v){Intent i= new Intent(this, Act2.class);i.putExtra(“key1”,vol1);i.putExtra(“key2”,vol2);::::::::::::::startActivity(i);}

Act2.javapublic void onCreate(Bundle saveInstantState){Super.onCreate(saveInstantState);setContentView(R.Layout.XMLFileName);:::::::::::::: //Business Logic::::::::::::::Bundle b=get Intent().getExtras();String s1=b.getString(“key1”);String s2=b.getString(“key2”);::::::::::::::::::::: //Business Logic operation ::::::::::::::}

*putExtra(): add input values (“key”,value)*getIntent(): source objref(i)*getExtras():getting source data*getString()-String format *getInt():Integer format *getFloat(): Float format …etc.

5. Switching with Result DataAct1.javaPublic static final int REQ_CODE =4;public void onCreate(Bundle saveInstantState){Super.onCreate(saveInstantState);setContentView(R.Layout.XMLFileName);:::::::::::::: //Business Logic}public void onClick(View v){Intent i= new Intent(this, Act2.class);i.putExtra(“key1”,vol1);

P a g e | 4

Page 5: Android Basic Tutorial

i.putExtra(“key2”,vol2);:::::::startActivityforResult(i);}public void onActivityResult(Req code, Res Code, Intent obj){If (REQ_CODE=Req code){Bundle b1=obj.getExtras();String s=b1.getString(“Keyres”);:::::::::::::: //Business Logic operation } }

Act2.javaPublic static final int RESULT_OK =2;public void onCreate(Bundle saveInstantState){Super.onCreate(saveInstantState);setContentView(R.Layout.XMLFileName);:::::::::::::: //Business LogicBundle b=get Intent().getExtras();String s1=b.getString(“key1”);String s2=b.getString(“key2”);::::::::::::::::::::: //Business Logic operation }public void finish(){Intent obj =new Intent(this,Act1.class);obj.putExtra(“keyres”,Volue);::::::setResult(I,RESULT_OK);super.finish();}

6 .Implicit Switching

a) Contact IntentIntent i=new Intent();i.setAction(android:Content.Intent.ACTION_VIEW);i.setData(ContactContract.Contacts.CONTENT_URI);startActivity(i);

(or)Intent i=new Intent(Intent.ACTION_VIEW,ContactsContract.Contacts.CONTENT_URI);

startActivity(i);

Manifest permission: READ_CONTACTS

P a g e | 5

Page 6: Android Basic Tutorial

b) Browser IntentIntent i=new Intent();i.setAction(android:Content.Intent.ACTION_VIEW);i.setData(Uri.parse(“http\\www.yahoo.com”));startActivity(i);(or)Intent i=new Intent(Intent.ACTION_VIEW,Uri.parse(“http\\www.google.com”));startActivity(i);

Manifest permission: INTERNET

c) Search IntentIntent i=new Intent(Intent.ACTION_WEB_SEARCH);i.putExtra(SearchManger.QUERY,"androidbboks”);startActivity(i);

Manifest permission: INTERNET

d) Map IntentIntent i= new Intent(Intent.ACTION_VIEW,Uri.parse(“geo:0,0?q=Hyderabad”); startActivity(i);

Manifest permission: INTERNET and ACCESS_FINE_LOCATION

e) Call Intent Intent i= new Intent(Intent.ACTION_CALL,Uri.parse(“tel:9876543210”)); startActivity(i);

Manifest permission: CALL_PHONE

7. Menu Design a) Options MenuI) Options Menu (with text items)public void onCreate(Bundle saveInstantState){Super.onCreate(saveInstantState);setContentView(R.Layout.XMLFileName);:::::::}public boolean onCreateOptionsMenu(Menu m){m.add(group Id, item Id, order, “Item Name”);:::::::return(true); }@Overridepublic boolean onOptionsItemSelected(MenuItem mi){switch(mi.getId()){

P a g e | 6

Page 7: Android Basic Tutorial

case : {:::::}case : {:::::}return(true)}

II) Options Menu (with Images)*create menu.xml files in (app/res/values/menu/menu.xml)@Override Methods

1) onCreateOptionsMenu(Menu m)2) onOptionsItemSelected(MenuItem mi)

public void onCreate(Bundle saveInstantState){Super.onCreate(saveInstantState);setContentView(R.Layout.XMLFileName);:::::::::::::: //Business Logic}

public boolean onCreateOptionsMenu(Menu m){MenuInflater mf=this.getMenuInflater();mf.Inflate(R.menu.menu,m);return(true);}public boolean onOptionsItemSelected(MenuItem mi){switch(mi.getId()){case : {:::::}return(true)}

b) Context MenuCreate String_array.xml in resource folder

@Override 1) onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo Menuinfo)2) onContextItemSelcted(MenuItem mi)

public class ContextMenu extends Activity{ListView lv; String countries[];public void onCreate(Bundle b){super.onCreate(b);setContentView(R.Layout.main);lv=this.getListView();countries=getResources().getStringArray(R.arrya.countries);ArrayAdapter<String> adp=new ArrayAdapter<String>(this,android.R.layout.Smiple_List_Item_1, countries);lv.setAdapter(adp);registerForContextMenu(lv);

P a g e | 7

Page 8: Android Basic Tutorial

}@Overridepublic void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo Menuinfo)AdapterContextMenuInfo acm=(AdapterContextMenuInfo)Menuinfo;menu.setHeaderTiltle(Countries(acm.position));menu.add(menu.NONE,1,meu.NONE,”Edit”);menu.add(menu.NONE,1,meu.NONE,”Map”);::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

Super.onCreateContextMenu(menu,v,menuinfo);}@OverridePublic void Boolean onCreateItemSelected(MenuItem mi){switch(mi.getId()){case: {:::::}case: {:::::}

}Return super.onContextItemSelected(mi);}}

8. Dialogs

a) Toast Messageb) Alert Dialogc) Input Dialogd) Date Picker Dialoge) Time Picket Dialogf) Progress Dialog

a) Toast MessageToast objref=Toast.makeText(context,”Messgae”,duration);objref.show();

*context: current class object (this)*duration: Toast.LENGTH_LONG, Toast.LENGTH_SHORT.

b) Alert Dialog

AlertDialog.Builder builder = new AlertDialog.Builder(this);builder.setIcon(R.drawable.image);builder.setTitle("Title......");

builder.setMessage("Message......");builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int which) {

P a g e | 8

O

Message

Title……..

Page 9: Android Basic Tutorial

::::::: ::::::: //Defining action for OK Button

:::::::}

});builder.show();

}}

c) Input DialogAlertDialog.Builder id = new AlertDialog.Builder(this);id.setTitle("Title......");final EditText et=new EditText(this);id.setView(et);

dsetPositiveButton("OK", new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int which) { :::::::

::::::: //Defining action for OK Button :::::::

}});id.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog, int which) {

:::::: ::::::: //Defining action for OK Button

:::::::}

});Id.show();

}

d) Time Picker DialogTimePickerDilog tp=new TimePickerDilog(this, null, hours,Minuts,true);tp.show();

e) Date Picker DialogDatePickerDilog dp=new DatePickerDilog(this, null, year,month,date);dp.show();

f) Progress Dialogfinal ProgressDialog pd=new ProgressDialog(this);

pd.setProgress(10);pd.setTitle("Progress Dialog");pd.setMessage("Progress is going on..");pd.show();

:::::: ::::::: //Logic

}

P a g e | 9

OK

Cance

Text Box

Title……..

Page 10: Android Basic Tutorial

new Thread(){public void run(){

try{Thread.sleep(2000);

}catch(Exception e){}pd.dismiss();

}}.start();

}

9. Activity Life Cycle Methods

public void onCreate(){super.onCreate();::::::::::::::::::::::::::::}

public void onStart(){super.onStart();::::::::::::::::::::::::::::}

public void onResume(){super.onResume();::::::::::::::::::::::::::::}

public void onRestart(){super.onRestart();::::::::::::::::::::::::::::}

public void onPause(){super.onPause();::::::::::::::::::::::::::::}

public void onStop(){super.onStop();::::::::::::::::::::::::::::}

public void onDestroy(){super.onDestroy();::::::::::::::::::::::::::::}

10. Multimedia

Manifest permission: RECORD_AUDIO //for recording audioManifest permission: WRITE_EXTERNA_STORAGE////for recording audio<uses-feature android:name=”android.Hardware.Camera”/>a) Working with Imagesb) Working with Audio Filesc) Working with Video Files d) Working with Animations

a) Working with Images

i) Resources Image

ImageView iv=(ImageView) findViewById(R.id.iv1);iv.setImageResources(R.drawable.image1);

ii) Capture Images

Intent camIntent=new Intent(android.provider.Mediastore.ACTION_IMAGE_CAPTURE);startActivityForResult(camIntent, req id);Public void onActivityForResult(req id, res id, Intent data){Bitmap thumbnail=(Bitmap)data.getExtras().get(“data”);ImageView iv=(ImageView) findViewById(R.id.iv1);iv.setImageBitmap(thumbnail);

P a g e | 10

Page 11: Android Basic Tutorial

b) Working with Audio Files

i) Playing Resource Songs

MediaPlayer mp=new MediaPlayer.create(this,R.raw.song1);mp.start();public void onDestroy(){mp.release();}}

iii) Playing Local Songs

Uri myuri=”Myfiles/downloads/song3” MediaPlayer mp=new MediaPlayer();Mp.setAudioStreamType(AudioManger,STREAM_MUSIC);Mp.setDataSource(this,myuri);Mp.prepare();Mp.start();

iv) Playing Remote Songs

Uri myuri=”http://www.songs.com” MediaPlayer mp=new MediaPlayer();Mp.setAudioStreamType(AudioManger,STREAM_MUSIC);Mp.setDataSource(this,myuri);Mp.prepare();Mp.start();

v) Recording Voice (Capture Audio)

MediaRecorder mr=new MediaRecorder();

mr.setAudioSource(mr.AudioSource.MIC);

mr.setOutputFormat(mr.OutputFormat.THREE_GPP);

mr.setAudioEncoder(mr.AudioEncoder.AMR_NB);

mr.setOutputFile(“sdcard/abc.3gp);

mr.prepare();

mr.start();

mr.stop();

mr.release();

P a g e | 11

Page 12: Android Basic Tutorial

c) Working with Video Files

i) Playing Video VideoView vv=(VideoView)findViewById(r.id.SurfaceView);vv.setVideoURI(Uri.parse(“android:resource://”+getPackagename()+”/”+R.raw.filename);vv.setMediaControler(new MediaControler(this));vv.requestFocus();

ii) Capturing Video

Intent videoIntent=new Intent(android.provider.Mediastore.ACTION_VIDEO_CAPTURE);

startActivityForResult(videoIntent, req id);

vv.setVideoURI(uri);

vv.start();

VideoFile uri=data.getData();

d) Working with Animations

i) AlphaAnimation – Controls transparency changesii) RotateAnimation – Controls rotationsiii) ScaleAnimation – Controls growing or shrinking iv) TranslateAnimation – Controls position changes

The four animation classes can be used for transitions between activities, layouts, views and so on. All these can be defined in the layout XML file as <alpha>, <rotate>, <scale>, and <translate>. They all to be contained within an AnimationSet <set>:res/anim/animated.xml

<alpha> attributes:android:fromAlpha=”0.0” android:toAlpha=”0” android:duration=”3000”

<rotate> attributes:android:fromDegrees=”0”, android:toDegrees=”180”android:pivotX=”50%”, android:pivotY=”50%”android:duration=”3000”

<scale> attributes:android:fromXScale=”0.0”, android:toXScale=”1.4”android:fromYScale=”0.0”,, android:toYScale=”1.4”android:pivotX=”50%”, android:pivotY=”50%”

<translate> attributes:android:fromXDelta=”100%p”, android:toXDelta=”0”android:fromYDelta=”100%p”,, android:toYDelta=”0”android:duration=”3000”

P a g e | 12

Page 13: Android Basic Tutorial

final ImageView im=(ImageView)findViewById(r.id.myimage);

final Animation an=AnimationUtils.loadAnimation(this,R.anim.Animated);

im.setVisibility(view.VISIBLE);

im.setVisibility(view.INVISIBLE);

im.startAnimation(an)

11. Services

Manifest : <Service android:name=”.ServiceClassName”/> //for user defined servicesServices Life Cycle

Service is executing background of the android application

1) Predefined Services2) User defined Services

Predefined Services:ServiceClassName objref=(ServiceClassName)this.getSystemService(Service type);

(or)

ServiceClassName objref=(ServiceClassName)this.getSystemService(context.Service type);

a) VibratorVibrator vb=(Vibrator)getSystemService(VIBRATOR_SERVICE);vb.vibrate(duration);

P a g e | 13

onRebind()

Service is shut down

onDestroy()

onUnbind()

Clint interacts with the service

onBind()

onCreate()

Service is started by

Service is shut down

onDestroy()

The service is stopped (no callback)

Service is running

onStart()

onCreate()

Service is started by

Page 14: Android Basic Tutorial

b) AlarmManagerAlarmManger am=(AlarmManager)getSystemService(ALARAM_SERVICE);

c) Location ManagerGPS Applications

d) Notification ManagerNotification window to display Notification messages like Missed calls, alarm information, reminders etc. NotificationManager nm=(NotificationMangaer)getSystemService(NOTIFICATION_SERVICE);To display notification on Title bar android API supports Notification()Notification n=new Notification(Icon, “Messgae”, Duration);Ex: n=new Notification(R.drawable.icon, “Reminder: Messages”, system.cuurentTimeMillis()+6000);Syntax to Display Notification Message in Notification Windown.setLatestEventInfo(this, Title, Message, Pending Intent);

e) Wi-Fi Manager Wi-Fi Applications

f) Bluetooth Adapterg) SMS Manager……etc.

SMSManager sms=(SMSManager)getSystemService(SMS_SERVICE);Sm.setTextMessage(“destination”, “msgcenter”, ”Message”, PendingIntent SentIntent, PendingIntent DeliverIntent);

*String destination=”9876543210”*String Message=”Hi world”*PendingIntent: Intent class used to achieve the switching between two activities after waiting some time.

Manifest permission: SEND_SMS

User Defined Servicespublic void ServiceClassName extends Service{public IBinder onBind(Intent is){return(null)}public void onCreate(){::::::::}public void onStart(Intent I, int StartId){:::::::::}public void onSestroy(){::::::::::}}

P a g e | 14

Page 15: Android Basic Tutorial

Call service into Activity classIntent is=new Intent(this, ServiceClassName.class);startService(is);stopService(is);

12. Text to Speech Conversion

TextToSpeech tts=new TextToSpeech(context,TextToSpeech.onInitListener objref);* TextToSpeech.onInitListener objref = Default TTS Engine supports by the android device (this)Methods of TextToSpeech Class

a) getDefaultEngine()Used to get the package name of the default speech synthesis engine, returns String value

b) getEngines()This will gives the all the list of Installed TTS engines returns List (interface)

c) getLanguage()Get the Language currently associated with the TTS engine

d) isSpeaking()If returns TRUE TTS Engine was busy with speaking otherwise returns FALSE

e) setLanguage(Local loc)It will set the TTS Language

f) setPitch()To set speech pitch normal (=1)/low (>1.0)/high (<1.0)

g) setSeechRate(float SpeechRate)To set speech rate normal (=1)/slower (>1.0)/faster (<1.0)

h) stop()Used to stop the current TTS Message temporarily

i) shutdown()Used to stop the current TTS Message permanently

j) onInit(Int Status)@Overridden Methodpublic void onInit(int Status){::::::::::::::::::::} *If Status=0 Activation of TTS Engine was done SUCCESSFULLY

k) speak(String text, int QUEUMODE, HashMap<String , String>prams)* QUEUMODE: QUEUE_ADD: This will add the new entry at the end of the play back. QUEUE_FLUSH: This will add the new entry at the end of the play back.

public class TextToSpeechActivity extends Activity implements TextToSpeech.onInitListener{TextToSpeech tts;public void onCreate(Bundle b)super.onCreate(b);setContentView(R.layout.xmlfile);::::::::::::::::::::::

tts=new TextToSpeech(this,this);

P a g e | 15

Page 16: Android Basic Tutorial

}public void onDestroy(){If(tts!=null){Tts.stop();Tts.shutdown();}Super.onDestroy();}Public void onInit(int Status);{If(Status=TextToSpeech.SUCCESS){Tts.setLanguage(Locale.us);Tts.setPitch(1.0);Tts.setSpeeakRate(1.0);//speakOut() /*user defined method.}public void speeakOut(){String text=text // whatever you want to speak out Tts.Speak(text,TextToSpeech.QUEUE_FLUSH,null);}}

13. Data Storage Methods (Internal and External Storage)

1) Phone Memory (Internal Storage).2) SD Card or External Storage.3) SQLite Database.

We can store any type of data in the form of files either in Internal (or) External Memory. Android was introduced Local Database to store the data permanently and securely, this is the part of Internal Memory (SQLite Data Base). Android API Supports predefined classes to work with Internal and External Memory, SQLite Database that means we can able to design Our own Android Application to store the data in any of the above locations. Internal and External Memory always supports storing of data in the form of files like Text files, Image Files, Audio and Video Files...etc., SQLite Database is used to store the data in the form of TABLES.

1) Working With Phone Memory (or) Internal Memory

It is a default memory comes along with every real device. It supports very less memory space compared to SD Card. In Internal Memory mainly we can perform two types of operations

1) Storing the data in the form of files.2) Retrieving data in the form of files.

Predefined Methods for Internal Memory

P a g e | 16

Page 17: Android Basic Tutorial

a) getFilesDir()It can be used to get the root path of the system directly where the internal files are saving by default.

b) getDir()This method can be used to get the current working directory path in the internal storage?

c) deleteFile()Used to delete files, which is available in the internal memory.Storing the data in the form of files

d) OpenFileOutput()It is a predefined method of Activity class used to open the given file from the internal memory and set writing mode. If the given file is not available which will create a new file in internal memory with the same file, this method returns FileOutputStream class Object Syntax:

FileOutputStream objref=OpenFileOutput (Path of the file, Mode of Access);

*path of the file = which represents location of the file.*Mode of Access = which represent Accessibility of file.Accessibility can be(a) MODE_PRIVATE (Only current activity allows working with the file).(b) MODE_PUBLIC (Any activity of same application allows working with the file).Example:FileOutputStream fos=OpenFileOutput (getFilesDir () +”/abc.txt”, MODE_PRIVATE);

Retrieving the data in the form of filese) OpenFileInput()

It is a predefined method of Activity class used to open the given file from the internal memory and in read mode this method returns FileInputStream class Object. Syntax:

FileInputStream objref=OpenFileInput (Path of the file);Example:

FileInputStream fis=OpenFileInput (getFilesDir () +”/abc.txt”);

Working with Text Files

In Internal Memory any text file not only can store and retrieve but also any data can be writing or reading operations can be done.

Write Data in to file:Data can be written into any file by using OutputStream Classes (DataOutputStream, OutputStreamWriter, ByteArrayOutputStream, BufferedOutputStream, and ObjectOutputStream).

Syntax: String s=”Hello Friends”;

FileOutputStream fos=OpenFileOutput (getFilesDir () +”/sample.txt”, MODE_PRIVATE);DataOutputStream dos=DataOutputStream(fos);dos.writeBytes(s);

(or)OutputStreamWriter sw=new OutputStreamWriter (fos);sw.write(s);fos.close();

P a g e | 17

Page 18: Android Basic Tutorial

Storing the files in our own directories:File f=new File (getFilesDir () +”/Sathya/Mydata/../..”);f.mkDir(); // Create new directory in default root directory.FileOutputStream fos=OpenFileOutput (getFilesDir () +” Sathya/Mydata /sample.txt”,

MODE_PRIVATE);OutputStreamWriter sw=new OutputStreamWriter (fos);sw.write(..);fos.close();

Reading Data from the text file:Data can be written into any file by using InputStream Classes (DataInputStream, ByteArrayInputStream, BufferedInputStream, and ObjectInputStream).Syntax:

FileInputStream fis=OpenFileInput (getFilesDir () +”/sample.txt”);DataInputStream dis=DataInputStream(fis);String s=dis.readLine();

(or)InputStreamReader sr=new InputStreamReader (fis);Sr.readLine();

Retrieving date from our own directories:Syntax:

FileInputStream fisd=OpenFileInput (getFilesDir () +”Sathya/Mydata/sample.txt”);DataInputStream dis=new DataInputStream (fisd);String s=dis.readLine();

2) Working with external memory or SD Card

External memory is optional and expandable memory, which can be used to store more data in file format compared to internal memory.Android API supports Environment Class to work with SD Card.

Methods for External Memory

a) getExternalStorageState()Used to get the state of the external storage device, this method returns the following states in

the form of string format.i) MEDIA_MOUNTED: If Media (SD Card) is present and Mounted (activation) with read and write access.ii) MEDIA_MOUNTED_READ_ONLY: Which represents media is present with read only access.iii) MEDIA_UNMOUNTED: Which represents media is present but no accessibility id given for reading (or) writing.iv) MEDIA_BAD_REMOVAL: It will be return if the media was removed before it was un mounted.v) MEDIA_CHECKING: It will be return if the media is present and being disk checked state.vi) MEDIA_REMOVED: This will be return if the media is not present.

P a g e | 18

Page 19: Android Basic Tutorial

b) getExternalStorageDirectory()Used to get the android external storage directory

c) getExternalStoragePublicDirectory(String type)Used to get top level public external storage directory files of particular type, Ex: Downloads, Ringtones, Videos…etc.

i) DIRECTORY_DOWNLODS ii) DIRECTORY_MOVIESiii) DIRECTORY_MUSICiv) DIRECTORY_PICTURES

Example: Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)//This will return path of the pictures gallery in android device.

d) getRootDirectory()It returns root directory of Android device (Myfiles/android…).

e) isExternalStorageRemovable()Returns “TRUE” if the SD Card is removable otherwise returns “FALSE”.

Working with external memory Syntax: String s= Environment,getExternalStorageState();if(s.equals(Environment.MEDIA_MOUNTED)//Checking media statusFile f= new File (Environment.getExternalStorageDirectory() +”/sample.txt”);

(or)File f= new File (Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_NOTIFICATIONS) +”/sample.txt”);FileOutputStream fos=new FileOutputStream(f);OutputStreamWriter osw=new OutputStreamWriter (fos);sw.write(..);

Working with Audio and Video Files

In general any Audio and Video files can be stored in either in internal or external memory in n-number of ways.

a) Storing Audio/Video files in External Memoryb) Storing Audio/Video files in Internal Memoryc) Retrieving Audio/Video files from Internal Memoryd) Retrieving Audio/Video files from External Memory

a) Storing Audio/Video files in External MemorySyntax:

FileOutputStream fos= new FileOutputStream (Environment.getExternalStorageDirectory () +”/Folder1/Folder2/…..+/FileName.extention).

Example: FileOutputStream fos= new FileOutputStream (Environment.getExternalStorageDirectory ()

+”/Sathya/MyMusic/Mysongs/Abc.MP3).

P a g e | 19

Page 20: Android Basic Tutorial

b) Storing Audio/Video files in Internal MemorySyntax:

FileOutputStream fos= OpenFileOutput (getFilesDir () +”/Folder1/Folder2/…..+/FileName.extention).

Example: FileOutputStream fos= OpenFileOutput (getFilesDir () +”/Sathya/MyMusic/ Abc.MP3).

c) Retrieving Audio/Video files from Internal MemorySyntax:

FileInputStream fis= OpenFileInput (getFilesDir () ”/Folder1/Folder2/…..+/FileName.extention).

Example: FileInputStream fos= OpenFileInput (getFilesDir () +”/Sathya/MyMusic//Abc.MP4).

d) Retrieving Audio/Video files from External MemorySyntax:

FileInputStream fis= new FileInputStream (Environment.getExternalStorageDirectory () +”/Folder1/Folder2/…..+/FileName.extention).

Example:FileInputStream fis= new FileInputStream (Environment.getExternalStorageDirectory ()

+”/Sathya/MyMusic/Mysongs/Abc.MP3).

Working with ImagesImages can be set to Image View or Storing in the SD Card/Internal memory with the following six

ways.

1) Getting image from drawable folder and set it in Image View.2) Capturing image from camera and set it to Image View.3) Getting image from External Memory and set to Image View.4) Getting image from Internal Memory and set to Image View.5) Getting image from External Memory and store it in to Internal Memory.6) Getting image from Internal Memory and store it in to External Memory.

1) Getting image from drawable folder and set it in ImageView.ImageView iv=(ImageView)findViewById(R.id.iv1);

iv.setImageResouce(r.drawable.myImage);

2) Capturing image from camera and set it to ImageView.public void onClick(View v){

Intent i=new Intent(android.provider.medeastore.ACTION_IMAGE_CAPTURE); startActivityforResul(i,REQ_CODE);

}public void onactivityforResult(int req, int res, Intent io){If(req=REQ_CODE){

P a g e | 20

Page 21: Android Basic Tutorial

Bitmap bm=(Bitmap)io.getExtras().get(“data”);ImageView iv=( ImageView)findViewById(R.id.image);iv.setImageBitmap(bm);}}

3) Getting image from External Memory and set to ImageView.

ImageView iv=( ImageView)findViewById(R.id.image);Bitmap bm=BitmapFactory.decodefile (Environment.getExternalStorageDirectory () +”Sathya/MyPictures/image1.png”);iv.setImageBitmap(bm);

4) Getting image from Internal Memory and set to ImageView.ImageView iv=( ImageView)findViewById(R.id.image);Bitmap bm=BitmapFactory.decodefile getFilesDir () +” MyPictures/image1.png”);iv.setImageBitmap(bm);

5) Getting image from External Memory and store it in to Internal Memory.//Reading Image for External MemoryFileInputStream fis=new FileInputStream(Environment.getExternalStorageDirectory()+”Sathya/Myimages/abc.png”);int size=fis.available();byte[] buffer=new byte[size];fis.read(buffer);

//Writing Image in to Internal MemoryFile F=new File(getFilesDir()+”MyImages/pictures”);f.mkDir();FileOutputStream fis= new FileOutputStream(getFilesDir()+”Sathya/Myimages/abc.png”);Fos.write(buffer);

6) Getting image from Internal Memory and store it in to External Memory.//Reading Image for Internal MemoryFileInputStream fis=new FileInputStream(getFilesDir()+”Sathya/Myimages/abc.png”);int size=fis.available();byte[] buffer=new byte[size];fis.read(buffer);

//Writing Image in to External MemoryFile F=new File(Environment.getExternalStorageDirectory()+”MyImages/Images”);f.mkDir();FileOutputStream fis= new FileOutputStream(Environment.getExternalStorageDirectory getFilesDir()+”Sathya/Myimages/abc.png”);Fos.write(buffer);

P a g e | 21

Page 22: Android Basic Tutorial

3) SQLite DatabaseSQLite Database is the collection of data used to store permanently and securely, every android

device by default supports SQLite Database. Instead of calling Java I/O routines to access this file from your program, you run Structured Query Language (SQL) statements. Through its helper classes and convenience methods, Android hides some of the syntax from you, but you still need to know a bit of SQL to use it.

SQLite Database supports various SQL commands to perform DML operations DDL StatementsA database file can have any number of tables. A table consists of rows, and each row has a certain number of columns. Each column of the table has a name and a data type (text string, number, and so forth). You define these tables and column names by first running Data Definition Language (DDL) statements. Here’s a statement that creates a table with three columns:

a) Create Table Syntax: Create Table <Table_Name> (col1 name, data type, constraint, col2 name, data type, constraint…etc.);

create table mytable (_id integer primary key autoincrement, name text, phone text);

One of the columns is designated as the PRIMARY KEY, a number that uniquely identifies the row. AUTOINCREMENT means that the database will add 1 to the key for every record to make sure it’s unique. By convention, the first column is always called _id. The _id column isn’t strictly required for SQLite, but later when we want to use an Android ContentProvider, we’ll need it.

public void onCreate(SQLiteDatabase db) {createDatabase(db);}private void createDatabase(SQLiteDatabase db) {db.execSQL("create table " + TABLE_NAME + "(" +ID + “integer primary key autoincrement not null,” +NAME + “text”+ ");");}

b) Insert RecordDML Syntax: Insert into <TableName> (Col1, col2…etc.) Values (vol1, vol2…etc.);

insert into mytable values(null, 'Steven King' , '555-1212' );insert into mytable values(null, 'John Smith' , '555-2345' );

P a g e | 22

Page 23: Android Basic Tutorial

insert into mytable values(null, 'Fred Smitheizen' , '555-4321' );

The values are specified in the same order you used in the CREATE TABLE statement. We specify NULL for _id because SQLite will figure that value out for us.

c) Update Record Syntax: update <TableName> set col1=vol1, col2=vol2….colN=volN [where condition];Example: Insert Student set Name=’PQR’, Marks=90.09 where Roll No=200;

d) Delete Record Syntax: Delete from <Table_Name> [where condition];Example: Delete from Student where Roll No=200;

e) Drop Table Syntax: Drop <TableName> Example: Drop Student

f) Select or Retrieve Data Syntax: Select col1, col2…colN from <TableName> [where condition];

select * from mytable where(_id=3);select name, phone from mytable where(name like "%smith%" );

In order to iterate over items in a database, we require an object of the Cursor class. To query the database, we use the query method along with appropriate arguments, most importantly: the table name, the column names for which we are extracting values.

SQLite Database Operations Mainly Depends on following predefined classes and Methods

1) SQLiteOpenHelper () – class used to create Schema and table/communication between android application and SQLite Database.(The constructor for the SQLiteOpenHelper class takes in a few arguments: context, database name, CursorFactory object, version number.)

public class SqlOpenHelper extends SQLiteOpenHelper {public static final String DBNAME = "tasksdb.sqlite";public static final int VERSION =1;public static final String TABLE_NAME = "tasks";public static final String ID= "id";public static final String NAME="name";

public SqlOpenHelper(Context context) {

super(context, DBNAME, null, VERSION);}@Override public void onCreate(SQLiteDatabase db){

P a g e | 23

Page 24: Android Basic Tutorial

db.execSQL(“Create Table cmd);}@Override public void onUpgrade(SQLiteDatabase db){db.execSQL(“drop table if exists TableName);db.execSQL(“Create Table cmd);}

Methods in SQLiteOpenHelper() classa) getDatabaseName()

Returns the name of the SQLiteDatabase being open as given to constructor b) getWritableDatabase()

Crete and/or open a database that will be write mode or read mode To get a handle on the SQL database you created, instantiate the class inheriting SQLiteOpenHelper:

SqlOpenHelper helper = new SqlOpenHelper(this);

SQLiteDatabase database= helper.getWritableDatabase();

Now, the SQLiteDatabase database can be used to load elements stored in the database, update and insert elements to it.

c) getReadableDatabase()Database opens only for read mode

d) onCreate(SQLiteDatabase)Called when the database is created first time

e) onUpgrade(SQLiteDatabase, int oldVersion, int newVersion)Called when the database is need to upgrade

f) onDowngrade(SQLiteDatabase, int oldVersion, int newVersion)Called when the database is need to downgrade

g) close()Close any opened database object

2) SQLiteDatabase() – class used to perform DML Operations Methods in SQLiteDatabase() class

h) Insert()Used to insert record into Database return type Long (returns row id)Syntax:Using insert () method and passing an object of ContentValues class. ContentValues provides something like a key-value pair,

*String table = TABLE_NAME* nullColumnHack = null values will added in the columns * ContentValues = Container holds the list of columns and values ContentValues cv=new ContentValues();cv.put(col1,vol1);cv.put(col2,vol2);

SQLiteDatabase db=getWritableDatabase();db.insert (“MyTable” null, cv);

P a g e | 24

Page 25: Android Basic Tutorial

i) update()Used to update one or more records into database table return type +int

update(String table, ContentValues, String Where Clause , String[]Where args);

ContentValues cv=new ContentValues();cv.put(_id,vol1);cv.put(col2,vol2);cv.put(col3,vol3);

String args [] = {1,2,3}SQLiteDatabase db=getWritableDatabase();db.update(“MyTable”, cv, “_id=?” args);ordb.update(“MyTable”,cv,null,null) all records will be updated

j) delete()Used to delete one or more records from database tabledelete(String table, String Where Clause , String[]Where args);String args [] = {1,3}SQLiteDatabase db=getWritableDatabase();db.delete(“MyTable”,”_id=?”, args); //1,3 records deleted

k) query() – return CursorUsed to select one or more records from database table, queryString table, String Columns, String Selection, String[]Selection args, String Having, String Orderby, String groupby));String columns[]={col1, col2};String args [] = {1,2};SQLiteDatabase db=getWritableDatabase();Cursor c=SQLiteDatabase.query(“MyTable”, columns[], ”_id=?”, args, null, null, null ); return c;//1,2 records col1,col2 retrieved

l) rawQuery() – return Cursor Used to select records from the table similar to query() but it allows direct SQL Commandsrawquery(“String SQL cmds, String[] selection args);String args [] = {1,2};SQLiteDatabase db=getWritableDatabase();Cursor c=SQLiteDatabase.rawquery(“select *from MyTable” where “_id=?”, args); return c;

3) execSQL(String sql)Used to execute a single SQL statement other than SELECT statement execSQL(“SQL Comands”);

4) Environment .getDataDirectory() – this method used get the root path of SQLite Database5) getPath() –Used to get the path of the database6) getVersion() - used to get the database version 7) isOpen() – returns true the database is currently open8) deleteDatabase(File file) - delete the database file

P a g e | 25

Page 26: Android Basic Tutorial

9) getMaximumSize() - get the size of the database 10) SimpleCursorAdapter(): to display the content

Understanding the SimpleCursorAdapter✓ this: Context: The context that is associated with the adapter.✓ R.layout.- layout: The layout resource identifier that defines the file to use for this list item.✓ reminderCursor - c: The database Cursor.✓ from - from: An array of column names that are used to bind data from the cursor to the view. ✓ to - - to: An array of view IDs that should display the column information from the from parameter. ✓ The to and from parameters create a mapping informing the SimpleCursorAdapter how to map data in the cursor to views in the row layout

14. Content ProviderOften the application generates data, which can be processed and analyzed by another

application. What is the safest way to achieve this, without giving direct access to our application's database?

Writing a custom Content Provider is the Android way to allow other applications to access data generated by our app.

ContetnProvider is a predefined android element used to make private data of SQLite database as public data, so that multiple applications can be able to access that data.

Content providers allow other applications to access the data generated by our app. For a custom content provider, we need to have the app database built up and we will be providing the wrapper over it for other applications. To make other apps aware that a content provider is available, declare it in

In Android contentprovider classified into two types 1) Predefined ContentProvider2) User defined ContentProvider

AndroidManifest.xml as:

<provider android:authorities="com.example.android.contentprovider"

android:name="MyContentProvider" />

Any piece of information managed by a ContentProvider is addressed through a URI that looks like this:content://authority/path/idwhere:• content:// is the standard required prefix.• authority is the name of the provider. Using your fully qualified package name is recommended to prevent name collisions.• path is a virtual directory within the provider that identifies the kind of data being requested.

P a g e | 26

Page 27: Android Basic Tutorial

• id is the primary key of a specific record being requested. To request all records of a particular type, omit this and the trailingslash. Android comes with several providers already built in, including the following:

• content://browser To share the browser history by multiple applications Predefined class : android.provider.Browser.BookMarkColumnsUri: Browesr.BOOKMARKS_URIManifest permission “ com.android.browser.permission.READ_HISTORY_BOOKMARKS”

• content://contacts anroid.provider.ContactsContract.Contacts” uri: “content://contacts/peopleManifest permission “ com.android.permission.READ_CONTACTS”

• content://callloganroid.provider.CallLog.Calls” uri: “CallLog.Calls.CONTENT_URI”Manifest permission “ com.android.permission.READ_CONTACTS”

To invoke with predefined ContentProvider we need to Activity.managedQuery() methodmanagedQuery()

It is a predefined method of Activity class can be used to move the data from Database to

ContentProvider (every content provider by default acting as result set or cursor adapter view, it is a

temporary memory Location in the primary memory) it will returns cursor

Syntax: managedQuery(Content uri. String[] projection, String Selection, String[] selection args, orderby);

*String[] projection : required fields from the table

*String Selection : where condition

3) User Defined ContentProvider Here the name refers to the class MyContentProvider which extends ContentProvider class. You need to override the following methods in this class.

public MycontentProvider extends ContentProvider{public void onCreate(){}

public int delete(Uri, String, String[]);{}

public String getType(Uri){}

public Long insert(Uri, ContentValues);{}

P a g e | 27

Page 28: Android Basic Tutorial

public Cursor query(Uri, String[], String, String[], String){}

public int on pdate(Uri, ContentValues, String, String[]){}

Manifest provider<Provider android:exported=”true”

android:name=”.MyProvider”authorities=”com.bened”/>

Every user defined contentprovider class should have user defined SQLiteOpenHelper() to manage user defined SQLiteDatabaseTo invoke with user defined ContentProvider we need to contentResolver() classcontentResolver ();This can be used to invoke with user defined ContentProvidercontentResolver cr=super.getcontentResolver();

Every user defined content provider can invoke with following method of contentResolver classCursor cs=cr.query(uri,projection,selection,selection arguments, orderby);

Any user define ContentProvider mus use the following fixed uri“content://com.bebed/contentable”

15) BroadcastReceiverBroadcast Receiver is a class in android used to intimate to the end user whenever any information or data is received form any application from the same device or another device.

public class <classname> extends BroadcastReceiver{@overridepublic void onReceive(context context, Intent intent){:::::}}

Manifest : <receiver android:name=”.BCRCN”/>

16) Networking

a) BluetoothUsed to connect other devices for sharing data Predefined class BluetoothAdapter();

Manifest permissions =”BLUETTOTH_ADMIN” = “BLUETOOTH”

Methods i. getDefaultAdapter()

P a g e | 28

Page 29: Android Basic Tutorial

This was returns BluetoothAdapter class objref with default properties of physical Adapter device( if that is working properly) otherwise returns null. BluettothAdapter ba= BluetoothAdapter.getDefaultAdapter();If(ba==null){//Bluetooth Adapter is not supported}else//Bluetooth supported }

ii. isEnabled()If it returns TRUE Bluetooth adapter is currently enabled and ready to use otherwise returns FALSEiii. enable()If it returns TRUE Bluetooth enabled otherwise returns FALSEiv. disable()If it returns TRUE Bluetooth disabled successfully otherwise returns FALSEv. isDiscovering()If it returns TRUE Bluetooth adapter is currently in discovering process (searching) vi. startDiscovering()Returns TRUE whenever local Bluetooth Adapter start the remote device discovering process vii. cancelDiscovering()If it returns TRUE Bluetooth adapter discovering process is canceled viii. listenUsingRfcommWithServiceRecord(String name, UUID uuid)This method can be used to request to pair with other device with secured connection (with protect with password request)ix. listenUsingosecureRfcommWithServiceRecord(String name, UUID uuid)This method can be used to request to pair with other device without secured connection x. getBoundedDevices()Returns set<BluetoothDevices> object that are Bounded (paired) to the local adapter xi. getAddress()Returns the hardware Address of the local Bluetooth Adapter in String formatxii. getName()Get the user friendly name of the local Bluetooth xiii. setName()Returns TRUE if the given user friendly name is set to local Bluetooth successfully

Bluetooth operations not only can be performed using predefined methods of Bluetooth adapter class but also using implicit Intent by passing default actions of same Bluetooth adapter class

Ex1: Intent enableIntent=new Intent(BluttothAdapter.ACTION_REQUEST_ENABLE);startActivityforResult(enableintent, 1);

Ex2: Intent discoverable=new Intent(BluttothAdapter.ACTION_REQUEST_DISCOVERABLE);Discoverable.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 3000);startActivityforResult(dicoverable, 1);

b) Wi-FiUsed to connect Local Systems for sharing of dataPredefine service class WifMangaer wm=(wifiManager)getSystemService(WIFI_SERVICE);

P a g e | 29

Page 30: Android Basic Tutorial

Manifest permissions =”ACCESS_WIFI_STATE” = “UPDATE_DEVICE_STATE” = “CHANGE_DEVICE_STATE”

Methodsi. setWifiEnabled(Boolean enabled)Used to enable and disable wifiii. startScan()Used to scan wifi networks iii. getScanResuluts()Returns the list of the latest scanned Networks returns List<ScanedReults)iv. isWifiEnabled()Returns TRUE if Wi-FI is enabled v. addNetwork(Wificonfiguration config)Used to add the new configured networks vi. enableNetwork(int netId)Allows previously configured networksvii. disableNetwork(int netId)Used to disable configured networksviii. disconnect()Used to disconnect the currently associated Wi-Fiix. getConnectionInfo()Returns the dynamic information about current Wi-Fi connection x. getConfiguredNetworks()Returns all the list of configured Networks xi. updateNetwork(WifiConfiguration confg)Used to update networks description of an existing configured networkxii. reconnect()Used to reconnect the currently active network if it is disconnected

c) GPRSMobil to connect any server system for sharing of data

Manifest permission: INTERNETPredefined classes a) WebView()-Used to load the web pages on layout files

b) WebSettings()-Used to enable/disable default settings public void GPRSConnection extends Activity{

public void onCreate(Bundle b){supre.onCreate(b);setContentView(R.layout.main);WebView w=(WebView)findViewById(R.id.webview);w.loadUrl(http://www.google.com);WebSettings ws=w.getSettings();ws.setJavaScriptenable(true);ws.setLoadWithOverViewMode(true);::::::::::::}}

HttpUrlConnection()

P a g e | 30

Page 31: Android Basic Tutorial

It is a predefined class java.net package used to establish connection between android applications to HTTP Server either for sending the request of to get the response from the Server.Steps to Send the Request (data) from android application to Server

Take Internet Permission in Manifest File Design any user defined layout (to give the provisioning to the end user to send data). Design Activity class which must contain following code

a) Create Object for HttpUrlConnection()b) Connect() - Establish connection between client and server

HttpUrlConnection huc=new HttpUrlConnection(url); *url = It should be used to taking permission from server provider huc.Connect();

c) Request data from Server with following codeOutputStream os=huc.getOutputStream();DataOutputStream dos=new DataOutputStream(os);

Steps to get the Response (data) from Server to android application Design user defined layout to display response data Design Activity class Read response data from server using InputStream Class

InputStream is=huc.getInputStream();DataInputStream dis=new DataInputStream(is);dis.readLine();is.close();

d) GPS

GPS is one of the mobile technologies used to find the current location of the device (Tracking of device) Manifest permissions: INTERNET

ACCESS_COARS_LOCATIONACCES_FINE_LOCATION

Location Based application Classes1) LocationManager()Used to find the current location of the device LocationManager lm=(LocationManager)getSystemService(context.LOCATION_SERVICE);Methodsi. requestLocationUpdate(--)Location Manager Class mainly depends upon LocationListener Interface, it is responsible to perform dynamic operations whenever the location settings has been changed Methods of LocationListener i. onLocationChanged()This will be called whenever current location has been changed ii. onProviderDisabled(String provider)This will be called whenever GPS is disabled.iii. onProviderEnabled(String provider)This will be called whenever GPS is enabled.iv. onStatusChanged(String provider, int Status, Bundle Extra)This will be executed whenever current network status has been changed2) MapActivity()3) MapView()4) MapController()5) GeoPoint()

P a g e | 31

Page 32: Android Basic Tutorial

Android Interview Questions and Answers 1. What is an Activity class and how to register activity in manifest file?2. What is an Intent class and write the logic to switch from one activity to other activity by passing name and address of student?3. What is the difference between bounded service and un-bounded service?4. Write the logic to play an audio song in the background of an android application?5. Write the logic to enable Wi-Fi service through android application?6. Write the logic to find current location using LocationManager Service?7. Explain the manifest file?8. What is the difference between SQLiteOpenHelper and SQLiteDatabase classes?9. What is the difference between WebView and MapView?10. What are the permissions should be taken while working with SD-card?11. What is widget?12. What is the function of an intent filter?13. What is the difference between onStop() and onPause()?14. Explain entire lifetime, visible lifetime & foreground lifetime?15. Write the various launch modes of an activity?16. What is the use of layout-weight in XML?17. What is the difference between Activity context and Application Context?18. What is meant by View Group in android? 19. What is the difference between Send Sticky Broadcast & send Broadcast?20. What is the usage of content resolver?21. Do we need to register content provider in androidmanifest.XML?22. What is NDK & Mention the use of NDK?23. Write the structure of Manifest file?24. What are the terms of dp, px, sp?25. What is nine-patch image?26. What is the usage of trace view & hierarchy view?27. What is latest version of android?28. Android: id="@+id/my button---------->what is + symbol?why we use that?29. How to install test app .apk file into phones?30. Activity Life Cycle?31. Different Kinds of Intents?32. Check the knowledge on AndroidManifest file, For example: Why do we need this file, What is the Role of this file in Android app development?.33. Different kinds of context?34. Kinds of Log debugger and Debugger Configuration35. How to debug the application on real device.36. How do you ensure that the app design will be consistent across the different screen resolutions37. Can you able to build custom views and how?38. What is onCreate (Bundle savedInstanceState), Have you used savedInstanceState when and why? 39. What is localization and how to achieve?40. Can you able to build custom views and how?41. When to use a service?

What is needed to make a multiple choice list with a custom view for each row?

P a g e | 32

Page 33: Android Basic Tutorial

Multiple choice list can be viewed by making the CheckBox android:id value be “@android:id /text1". That is the ID used by Android for the CheckedTextView in simple_list_item_multiple_choice.

Explain about the exceptions of Android.The following are the exceptions that are supported by Android

InflateException : When an error conditions are occurred, this exception is thrown Surface.OutOfResourceException: When a surface is not created or resized, this exception is thrown SurfaceHolder.BadSurfaceTypeException: This exception is thrown from the lockCanvas() method, when

invoked on a Surface whose is SURFACE_TYPE_PUSH_BUFFERS WindowManager.BadTokenException: This exception is thrown at the time of trying to add view an

invalid WindowManager.LayoutParamstoken What’s the difference between file, class and activity in android?

File – It is a block of arbitrary information, or resource for storing information. It can be of any type.Class – Its a compiled form of .Java file . Android finally used this .class files to produce an executable apkActivity – An activity is the equivalent of a Frame/Window in GUI toolkits. It is not a file or a file type it is just a class that can be extended in Android for loading UI elements on view.

What is a Sticky Intent?

sendStickyBroadcast() performs a sendBroadcast (Intent) that is “sticky,” i.e. the Intent you are sending stays around after the broadcast is complete, so that others can quickly retrieve that data through the return value of registerReceiver (BroadcastReceiver, IntentFilter). In all other ways, this behaves the same as sendBroadcast(Intent).

One example of a sticky broadcast sent via the operating system is ACTION_BATTERY_CHANGED. When you call registerReceiver() for that action — even with a null BroadcastReceiver — you get the Intent that was last broadcast for that action. Hence, you can use this to find the state of the battery without necessarily registering for all future state changes in the battery.

Describe Android Application Architecture.

Android Application Architecture has the following components:• Services – like Network Operation• Intent – To perform inter-communication between activities or services• Resource Externalization – such as strings and graphics• Notification signaling users – light, sound, icon, notification, dialog etc.• Content Providers – They share data between applications

What kind of open-source project is Android?

Google oversees the development of the core Android open-source platform, and works to create robust developer and user communities. For the most part the Android source code is licensed under the permissive Apache Software License 2.0, rather than a “copyleft” license. The main reason for this is because our most important goal is widespread adoption of the software, and we believe that the ASL2.0 license best achieves that goal.

You can find more information on this topic at our Project Philosophy and Licensing pages.

Introduction Android:

P a g e | 33

Page 34: Android Basic Tutorial

Android Introduction: Android is an open source operating system for mobile devices that includes middleware and key

applications, and uses a modified version of the Linux kernel. It was initially developed by Android Inc. It allows developers to write managed code in the Java language, controlling the device via Google-

developed Java libraries…..The Android SDK includes a comprehensive set of development tools . These include a debugger, libraries, a handset emulator (based on QEMU), documentation, sample code, and tutorials. Currently supported development platforms include x86-architecture computers running Linux ,Mac OS X 10.4.8 or later, Windows XP or Vista. Android does not use established Java standards, i.e. Java SE and ME. This prevents compatibility among Java applications written for those platforms and those for the Android platform. Android only reuses the Java language syntax, but does not provide the full-class libraries and APIs bundled with Java SE or ME

What is android? Android is a software stack for mobile devices which has Operating System, middleware and some key

applications. The application executes within its own process and its own instance of Dalvik Virtual Machine. Many Virtual Machines run efficiently by a DVM device. DVM executes Java language?s byte code which later transforms into .dex format files.

What are the advantages of Android?The following are the advantages of Android:* Features like weather details, live RSS feeds, opening screen, icon on the opening screen can be customized* The customer will be benefited from wide range of mobile applications to choose, since the monopoly of wireless carriers like AT&T and Orange will be broken by Google Android.* Innovative products like the location-aware services, location of a nearby convenience store etc., are some of the additive facilities inAndroid.Components can be reused and replaced by the application framework.*Optimized DVM for mobile devices*SQLite enables to store the data in a structured manner.*Supports GSM telephone and Bluetooth, WiFi, 3G and EDGE technologies*The development is a combination of a device emulator, debugging tools, memory profiling and plug-in for Eclipse IDE.

Features of Android : Application framework enabling reuse and replacement of components Dalvik virtual machine optimized for mobile devices Integrated browser based on the open source WebKit engine Optimized graphics powered by a custom 2D graphics library; 3Dgraphics based on the OpenGL ES 1.0 specification (hardware acceleration optional) SQLite for structured data storage Media support for common audio, video, and still image formats (MPEG4, H.264, MP3, AAC, AMR, JPG, PNG, GIF) GSM Telephony (hardware dependent) Bluetooth, EDGE, 3G, and WiFi (hardware dependent) Camera, GPS, compass, and accelerometer (hardware dependent)

P a g e | 34

Page 35: Android Basic Tutorial

Rich development environment including a device emulator, tools for debugging, memory and performance profiling, and a plugin for the Eclipse IDE.

Explain about the Android Exceptions? The following are the exceptions that are supported by Android

* InflateException : When an error conditions are occurred, this exception is thrown* Surface.OutOfResourceException: When a surface is not created or resized, this exception is thrown* SurfaceHolder.BadSurfaceTypeException: This exception is thrown from the lockCanvas() method, when invoked on a Surface whose is SURFACE_TYPE_PUSH_BUFFERS* WindowManager.BadTokenException:

This exception is thrown at the time of trying to add view an invalid WindowManager.LayoutParamstoken.

Describe the APK format?The APK file is compressed the AndroidManifest.xml file, application code (.dex files), resource files, and other files. A project is compiled into a single .apk file.

What is an adb ?Android Debug Bridge, a command-line debugging application shipped with the SDK. It provides tools to browse the device, copy tools on the device, and forward ports for debugging.

What is an Application ?A collection of one or more activities, services, listeners, and intent receivers. An application has a single manifest, and is compiled into a single .apk file on the device.

What is a Content Provider ?A class built on ContentProvider that handles content query strings of a specific format to return data in a specific format. See Reading and writing data to a content provider for information on using content providers.

What is a Dalvik ?The name of Android’s virtual machine. The Dalvik Virtual Machine is an interpreter-only virtual machine that executes files in the Dalvik Executable (.dex) format, a format that is optimized for efficient storage and memory-mappable execution. The virtual machine is register-based, and it can run classes compiled by a Java language compiler that have been transformed into its native format using the included “dx” tool.

The Virtual Machine runs on top of Posix-compliant operating systems, which it relies on for underlying functionality (such as threading and low level memory management). The Dalvik core class library is intended to provide a familiar development base for those used to programming with Java Standard Edition, but it is geared specifically to the needs of a small mobile device.

What is Drawable?A compiled visual resource that can be used as a background, title, or other part of the screen. It is compiled into an android.graphics.drawable subclass.

What is Intent?A class (Intent) that contains several fields describing what a caller would like to do. The caller sends this intent to Android’s intent resolver, which looks through the intent filters of all applications to find the activity most suited to handle this intent. Intent fields include the desired action, a category, and a data string, the MIME type of the data, a handling class, and other restrictions.

What is an Intent Filter?Activities and intent receivers include one or more filters in their manifest to describe what kinds of intents or messages they can handle or want to receive. An intent filter lists a set of requirements, such as data type, action requested, and URI format, that the Intent or message must fulfill. For Activities, Android searches for the Activity with the most closely matching valid match between the Intent and the activity filter. For messages, Android will forward a message to all receivers with matching intent filters.

P a g e | 35

Page 36: Android Basic Tutorial

What is an Intent Receiver?An application class that listens for messages broadcast by calling Context.broadcastIntent

What is a Layout resource?An XML file that describes the layout of an Activity screen.

What is a Manifest?An XML file associated with each Application that describes the various actives, intent filters, services, and other items that it exposes.

What is a Resource?A user-supplied XML, bitmap, or other file, entered into an application build process, which can later be loaded from code. Android can accept resources of many types; see Resources for a full description. Application-defined resources should be stored in the res/ subfolders.

What is a Service?A class that runs in the background to perform various persistent actions, such as playing music or monitoring network activity.

What is a Theme?A set of properties (text size, background color, and so on) bundled together to define various default display settings. Android provides a few standard themes, listed in R.style (starting with “Theme_”).

What is a URIs?Android uses URI strings both for requesting data (e.g., a list of contacts) and for requesting actions (e.g., opening a Web page in a browser). Both are valid URI strings, but have different values. All requests for data must start with the string “content: //”. Action strings are valid URIs that can be handled appropriately by applications on the device; for example, a URI starting with “http://” will be handled by the browser.

Can I write code for Android using C/C++?Yes, but need to use NDKAndroid applications are written using the Java programming language. Android includes a set of core libraries that provides most of the functionality available in the core libraries of the Java programming language. Every Android application runs in its own process, with its own instance of the Dalvik virtual machine. Dalvik has been written so that a device can run multiple VMs efficiently. The Dalvik VM executes files in the Dalvik Executable (.dex) format which is optimized for minimal memory footprint. The VM is register-based, and runs classes compiled by a Java language compiler that have been transformed into the .dex format by the included “dx” tool.Android only supports applications written using the Java programming language at this time.

What is an action?A description of something that an Intent sender desires.

What is activity?A single screen in an application, with supporting Java code.

What is intent?A class (Intent) describes what a caller desires to do. The caller sends this intent to Android’s intent resolver, which finds the most suitable activity for the intent. E.g. opening a PDF file is intent, and the Adobe Reader is the suitable activity for this intent.

How is nine-patch image different from a regular bitmap?It is a resizable bitmap resource that can be used for backgrounds or other images on the device. The NinePatch class permits drawing a bitmap in nine sections. The four corners are unscaled; the four edges are scaled in one axis, and the middle is scaled in both axes.

What languages do Android support for application development?Android applications are written using the Java programming language.

What is a resource?

P a g e | 36

Page 37: Android Basic Tutorial

A user-supplied XML, bitmap, or other file, injected into the application builds process, which can later be loaded from code.

How will you record a phone call in Android? How to get a handle on Audio Stream for a call in Android?Permissions.PROCESS_OUTGOING_CALLS: Allows an application to monitor, modify, or abort outgoing calls.

1. Explain the Architecture of android?a. Top -> Applications (Contacts, Browser, Phone, etc)b. Below Applications -> Application Framework(Activity Manager, Window Manager, Content Providers,

View System, Package manager,Telephony manager, Resource, Notification, Location managers)

c. Below Application Framework -> System Libraries(Like Sqlite, webkit, SSL, OpenGL, Media Framework etc) & Android Runtime( Core Libraries and DVM)

d. At last -> Linux Kernel (which composed of drivers like display, camera etc.)2. What is an Activity?

A single screen in an application, with supporting Java code, An activity presents a visual user interface for one focused endeavor the user can undertake. For example, an activity might present a list of menu items users can choose from or it might display photographs along with their captions. Each one is implemented as a subclass of the Activity base class.

3. What are fragments in Android Activity?A Fragment represents a behavior or a portion of user interface in an Activity. And it is a self-contained component with its own UI and lifecycle.

4. What is Intent?A class (Intent) which describes what a caller desires to do. The caller will send this intent to

Android's intent resolver, which finds the most suitable activity for the intent. E.g. opening a PDF document is an intent, and the Adobe Reader apps will be the perfect activity for that intent (class).

5. What is a Sticky Intent?sendStickyBroadcast() performs sendBroadcast(Intent) known as sticky, i.e. the Intent you are

sending stays around after the broadcast is complete, so that others can quickly retrieve that data through the return value of registerReceiver(BroadcastReceiver, IntentFilter). In all other ways, this behaves the same as sendBroadcast(Intent). One example of a sticky broadcast sent via the operating system is ACTION_BATTERY_CHANGED. When you call registerReceiver() for that action -- even with a null BroadcastReceiver -- you get the Intent that was last broadcast for that action. Hence, you can use this to find the state of the battery without necessarily registering for all future state changes in the battery.

6. What is an action?A description of something that an Intent sender desires

7. What is a service?A service doesn’t have a visual user interface, but rather runs in the background for an indefinite period of time.For example, a service might play background music as the user attends to other matters, or it might fetch data over the network or calculate something and provide the result to activities that need it.Each service extends the Service base class.

8. What is a Broadcast receiver?A broadcast receiver is a component that does nothing but receives and reacts to broadcast announcements.

P a g e | 37

Page 38: Android Basic Tutorial

For example, announcements that the timezone has changed, that the battery is low or that the user changed a language preference.

All receivers extend the BroadcastReceiver base class.Broadcast receivers do not display a user interface. However, they may start an activity in response to the information they receive,or they may use the Notification Manager to alert the user like(flashing the backlight, vibrating the device, playing a sound).

9. What is a content provider?A content provider makes a specific set of the application’s data available to other applications.The content provider extends the ContentProvider base class to implement a standard set of methods that enable other applications to retrieve and store data of the type it controls. However, applications do not call these methods directly. Rather they use a ContentResolver object and call its methods instead.

10. What language does Android support for application development?Android applications are written using the Java programming language.

11. What is a resource?A user-supplied XML, bitmap, or other file, injected into the application build process, which can later be loaded from code.

12. How do you define the user interface?XML Format is the best.

13. Does Android support the Bluetooth serial port profile?Yes.

14. Can an application be started on power up?Yes.

15. What is the APK format?The APK file is compressed AndroidManifest.xml file with extension .apk. It also includes the application code (.dex files), resource files, and other files which are compressed into a single .apk file.

16. What is .dex extension ?Android programs are compiled into .dex (Dalvik Executable) files, which are in turn zipped into a single .apk file on the device. .dex files can be created by automatically translating compiled applications written in the Java programming language.

17. How to Translate in Android?The Google translator translates the data of one language into another language by using XMPP to transmit data. You can type the message in English and select the language which is understood by the citizens of the country in order to reach the message to the citizens.

18. What is needed to make a multiple choice list with a custom view for each row?

Multiple choice list can be viewed by making the CheckBox android:id value be “@android:id /text1". That is the ID used by Android for the CheckedTextView in simple_list_item_multiple_choice.

19. What dialog boxes are supported in android?

Android supports 4 dialog boxes:Alert Dialog: An alert dialog box supports 0 to 3 buttons and a list of selectable elements, including check boxes and radio buttons. Among the other dialog boxes, the most suggested dialog box is the alert dialog box.Progress Dialog: This dialog box displays a progress wheel or a progress bar. It is an extension of Alert Dialog and supports adding buttons.DatePickerDialog: This dialog box is used for selecting a date by the user.TimePickerDialog: This dialog box is used for selecting time by the user.

20. Explain about the exceptions of Android?

P a g e | 38

Page 39: Android Basic Tutorial

The following are the exceptions that are supported by Android* InflateException : When an error conditions are occurred, this exception is thrown* Surface.OutOfResourceException: When a surface is not created or resized, this exception is thrown* SurfaceHolder.BadSurfaceTypeException: This exception is thrown from the lockCanvas() method, when invoked on a Surface whose is SURFACE_TYPE_PUSH_BUFFERS* WindowManager.BadTokenException: This exception is thrown at the time of trying to add view an invalid WindowManager.LayoutParamstoken.

21. What are the features of Android?

*Components can be reused and replaced by the application framework.*Optimized DVM for mobile devices*SQLite enables to store the data in a structured manner.*Supports GSM telephone and Bluetooth, WiFi, 3G and EDGE technologies*The development is a combination of a device emulator, debugging tools, memory profiling and plug-in for Eclipse IDE.

22. How will you record a phone call in Android? or How to handle on Audio Stream for a call in Android?

Permissions.PROCESS_OUTGOING_CALLS: Will Allows an application to monitor, modify, or abort outgoing calls. So through that we can monitor the Phone calls.

23. What's the difference between class, file and activity in android?Class - The Class file is compiled from .java file. Android will use this .class file to produce the executable apk.File - It is a block of resources, srbitrary information. It can be any file type. Activity - An activity is the equivalent of a Frame/Window in GUI toolkits. It is not a file or a file type it is just a class that can be extended in Android for loading UI elements on view.

24. What are the advantages of Android?

The following are the advantages of Android:* The customer will be benefited from wide range of mobile applications to choose, since the

monopoly of wireless carriers like Orange and AT&T will be broken by Google Android.* Features like weather details, live RSS feeds, opening screen, icon on the opening screen can be customized.* Innovative products like the location-aware services, location of a nearby convenience store etc., are some of the additive facilities in Android.

25. How many ways data stored in Android?

1. SharedPreferences 2. Internal Storage 3. External Storage 4. SQLite Database 5. Network connection

26. What is View in Android?Views are the base class for all visual interface elements (commonly known as controls or widgets).All UI controls, including the layout classes, are derived for View.

27. What View Group in Android?View Groups are extensions of the View class that can contain multiple child View.Extend the ViewGroup class to create compound controls made up of interconnected child Views.

28. What is Pending Intent?The PendingIntent class provides a mechanism for creating Intents that can be fired by another application at a later time. A pending Intent is commonly used to package an Intent will be fired in

P a g e | 39

Page 40: Android Basic Tutorial

response to a future event, such as a widget View being clicked or a Notification being selected from the notification panel.

29. What is Adapter?Adapters are bridging classes that bind data to Views (such as List Views) used in the user interface.The adapter is responsible for creating for creating the child Views used to represent each item within the parent View, and providing access to the underlying data.

30. What is a DDMS?Dalvik Debug Monitor Service, a GUI debugging application shipped with the SDK. It provides screen capture, log dump, and process examination capabilities.

31. What is an adb?Android Debug Bridge, a command-line debugging application shipped with the SDK. It provides tools to browse the device, copy tools on the device, and forward ports for debugging.

32. Explain Structure of Manifest.xml File?Every application must have an AndroidManifest.xml file (with precisely that name) in its root directory. The manifest presents essential information about the application to the Android system, information the system must have before it can run any of the application's code.

Following Are the Contents of manifest.xml File.• Application• Activity• Services• Broadcast Receivers• Permissions• Instrumentation• Minimum API Level

33. How will you pass the data to sub-Activities?We can use Bundles to pass data to sub-activities. There are like HashMaps that and take trivial

data types. These Bundles transport information from one Activity to another.code - Bundle b = new Bundle();b.putString("EMAIL", "[email protected]");i.putExtras(b); // where i is the intent

34. What is AAPT?AAPT is short for Android Asset Packaging Tool. This tool provides developers with the ability to deal with zip-compatible archives, which includes creating, extracting as well as viewing its contents.

35. What is the importance of having an emulator within the Android environment?The emulator lets developers “play” around an interface that acts as if it were an actual mobile device. They can write and test codes, and even debug. Emulators are a safe place for testing codes especially if it is in the early design phase.

36. What is Orientation?Orientation, which can be set using setOrientation(), dictates if the LinearLayout is represented as a row or as a column. Values are set as either HORIZONTAL or VERTICAL.

P a g e | 40

Page 41: Android Basic Tutorial

37. What is ANR?ANR is short for Application Not Responding. This is actually a dialog that appears to the user whenever an application have been unresponsive for a long period of time.

38. How can the ANR be prevented?One technique that prevents the Android system from concluding a code that has been responsive for a long period of time is to create a child thread. Within the child thread, most of the actual workings of the codes can be placed, so that the main thread runs with minimal periods of unresponsive times.

39. When does ANR occur?The ANR dialog is displayed to the user based on two possible conditions. One is when there is no response to an input event within 5 seconds, and the other is when a broadcast receiver is not done executing within 10 seconds.

40. What is AIDL?AIDL, or Android Interface Definition Language, handles the interface requirements between a client and a service so both can communicate at the same level through interprocess communication or IPC. This process involves breaking down objects into primitives that Android can understand. This part is required simply because a process cannot access the memory of the other process.

41. What data types are supported by AIDL?

AIDL has support for the following data types:-string-charSequence-List-Map-all native Java data types like int, long, char and Boolean.

42. What is the difference between a regular bitmap and a nine-patch image?In general, a Nine-patch image allows resizing that can be used as background or other image size requirements for the target device. The Nine-patch refers to the way you can resize the image: 4 corners that are unscaled, 4 edges that are scaled in 1 axis, and the middle one that can be scaled into both axes.

43. What do you think are some disadvantages of Android?Given that Android is an open-source platform, and the fact that different Android operating systems have been released on different mobile devices, there’s no clear cut policy to how applications can adapt with various OS versions and upgrades. One app that runs on this particular version of Android OS may or may not run on another version. Another disadvantage is that since mobile devices such as phones and tabs come in different sizes and forms, it poses a challenge for developers to create apps that can adjust correctly to the right screen size and other varying features and specs.

44. What are the multimedia features involved in making Android popular?There is the demand for the rich multimedia that involves many features that are used till now to

make the Android market more popular in all the phases. The application includes the following:

• Mixable audio effects – developer can easily create audio environments using the API key that is provided with it like creating equalization, bass boost, headphone feature, etc. The android provide the tools that can be used to mix the audio effects and apply it.• There is also support for new media formats like VP8 open video compression format that uses a

P a g e | 41

Page 42: Android Basic Tutorial

container format that can run on all the platforms and add the support for AAC and AMR encoding. The applications provided allow higher quality video to be captured. • The application allows the access to multiple cameras that allows the use of APIs to include the camera and its properties in one. The platform provides the application to include the camera with high and low resolution.

45. What are the different data types used by Android?

The data can be passed between many services and activities using the following data types:• Primitive Data Types: are used to share the activities and services of an application by using the command as Intent.putExtras(). This primitive data passes the command to show the persistent data using the storage mechanism. These are inbuilt data types that are used with the program. They provide simple implementation of the type and easy to use commands. • Non-Persistent Objects: are used to share complex and non-persistent objects. These are user-defined data types that are used for short duration and are also recommended to be used. These types of objects allow the data to be unique but it creates a complex system and increase the delay.

46. What are the methods to avoid memory leaks in Android?

Android applications are well bundled with the memory but they have a drawback of running lots of application that keeps in the memory to make the processing faster. The more application in the memory, the faster will be the switch between the applications. The memory leaks can be avoided by changing the context. The context is used for many operations but it is used to access the resources on android. The widgets have a context parameter in their constructors. There are mainly two types of context: either activity or application. The program is as follows:@Overrideprotected void onCreate(Bundle state) {super.onCreate(state);TextView label = new TextView(this);label.setText("Test memory leak");setContentView(label);}if the context is having leaks in it then the activity then there is a possibility of the leaks of memory. The leaking of the entire activity can be checked. The system will automatically create and destroy one of the activities by default. Android will reload the application by using the rotation policy. And it will keep the entire static field maintained.

47. What are the various ways an Android developer can apply multi-threading to their app? Be specific, and give examples.

Since Android uses the Java language it provides all the normal threading mechanisms as all Java-based implementations.You create a Thread by either (a) sub-classing the Thread class with your own and over-loading the run() method to perform your background task, or (b) you create an instance of the Thread class by giving it an instance of the Runnable interface, and overload the run() method of that interface to perform your background task. Option (b) is preferred by far in most circumstances.

P a g e | 42

Page 43: Android Basic Tutorial

Android, however, provides additional threading mechanisms over and above those provided by Java, and they tend to resolve some of the most interesting dilemmas in Java programming.In Android you have the following additional mechanisms:1) AsyncTask2) Handler3) runOnUiThread()4) IntentService (for Service implementations)

So, depending upon what your needs are, you can greatly simplify your code by opting for the use of one of these mechanisms.

For instance, the AsyncTask class provides a very nice encapsulation of creating a Java Thread, providing thread-correct calls for pre/post processing, and automatically uses a thread pool behind the scenes to efficiently use thread resources. All this and provides a very simple 4 method sub-classing interface where you can write just your background code within a single method, and the AsyncTask class will handle cross-thread messaging for you. You have to know, however, that AsyncTask uses a Handler instance internally, so if you're launching this from a Thread that doesn't use a MessageQueue, then this may not work properly for you.

runOnUiThread() does just what it says, it will take a Runnable instance, and run it in the thread space of the main, or "UI", thread in Android. This is a handy feature when you just want a simple means of interacting with the user interface.

Although specific to Service implementations, which should always be threaded, the IntentService provides automatic single-threading for simple implementations, saving tons of code the Service developer.

P a g e | 43