• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Android Basic Components
 

Android Basic Components

on

  • 11,553 views

 

Statistics

Views

Total Views
11,553
Views on SlideShare
11,150
Embed Views
403

Actions

Likes
4
Downloads
489
Comments
3

23 Embeds 403

http://devcave-areegad.blogspot.com 242
http://devcave-areegad.blogspot.in 76
http://devcave-areegad.blogspot.com.au 28
http://devcave-areegad.blogspot.nl 8
http://devcave-areegad.blogspot.fr 7
http://devcave-areegad.blogspot.kr 6
http://devcave-areegad.blogspot.co.uk 6
http://devcave-areegad.blogspot.ca 6
http://devcave-areegad.blogspot.de 3
http://devcave-areegad.blogspot.it 3
http://devcave-areegad.blogspot.co.il 3
http://devcave-areegad.blogspot.hk 2
http://devcave-areegad.blogspot.no 2
http://devcave-areegad.blogspot.dk 2
http://devcave-areegad.blogspot.gr 1
http://translate.googleusercontent.com 1
http://devcave-areegad.blogspot.ro 1
http://devcave-areegad.blogspot.pt 1
http://devcave-areegad.blogspot.be 1
http://devcave-areegad.blogspot.tw 1
http://devcave-areegad.blogspot.ie 1
http://devcave-areegad.blogspot.hu 1
http://devcave-areegad.blogspot.com.es 1
More...

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel

13 of 3 previous next Post a comment

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
  • very nice .. Thanks for sharing ..

    Keep on sharing some more like this one...
    Are you sure you want to
    Your message goes here
    Processing…
  • Nice post!! thanks… Even this website http://www.compiletimeerror.com/2013/01/directorystructure-of-android-project.html also addresses something similar.. Have a look, may be useful…
    Are you sure you want to
    Your message goes here
    Processing…
  • very nice presentation.
    Thank for sharing...
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Android Basic Components Android Basic Components Presentation Transcript

    • Android  Basic  Components   Jussi  Pohjolainen   Tampere  University  of  Applied  Sciences  
    • APP  FUNDAMENTALS  
    • App  Fundamentals   •  Android  app  lives  in  its  own  world   – Own  process,  app  files  only  visible  to  the  app   •  Apps  can  make  use  of  other  apps,  informaDon   sharing,  moving  between  apps   •  Apps  are  build  using  Android  components   •  Every  app  holds  a  applicaDon  descripDon  file   (AndroidManifest.xml)   – In  the  file  you  define  the  android  components  
    • <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="fi.organization.test" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="18" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="fi.organization.test.MainActivity" 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> </manifest>
    • uses-sdk •  Declare  your  app  compaDbility   – minSDKVersion •  Lowest  level  API  where  your  app  works   – targetSDKVersion •  Highest  API  level  against  where  you  have  designed  and   tested  your  app  
    • Components   •  Android  app  is  built  using  components   –  Ac9vity:  User  visible  Window   –  Service:  Background  service  (no  UI)   –  Broadcast  Receiver:  receiving  broadcasts  from  apps   and  system  services   –  Content  provider:  Provides  content  to  apps   •  Components  are  separate  building  blocks  that   can  be  accessed  by  other  apps!   •  Components  are  usually  declared  in  applicaDon   manifest  
    • ApplicaDon  Components   1.  Ac9vi9es  and  Intents   2.  Services   3.  Broadcast  receivers   4.  Content  provides    
    • 1.  AcDviDes   •  An  ac&vity  is  a  single,  focused  thing  that  the   user  can  do     – Equivalent  to  Frame  or  Window  in  GUI  toolkits   •  Subclass  of  Activity  –  class   •  One  app  may  have  one  or  several  acDviDes   •  Each  acDvity  is  given  a  default  window  to   draw  in   •  Window  consists  of  views  (widgets)  
    • Some  AcDviDes  from  Android  2.x  
    • AcDvity  Stack   •  Android  keeps  navigaDon  history  of  acDviDes   the  user  has  visited:  AcDvity  Stack  or  the  Back   Stack   •  Pressing  Back  displays  the  previous  AcDvity!   •  User  cannot  go  further  than  the  last  visit  of   home  
    • Back  Stack  
    • About  Tasks   •  Task  is  a  sequence  of  acDviDes   •  Task  can  hold  acDviDes  from  several  apps   •  AcDvity  that  starts  the  task  is  called  root   acDvity   – Usually  started  from  home  screen   •  New  task  is  started  when  new  app  is   launched.  Also  new  task  can  be  started  on   certain  acDviDes  (opening  browser,  maps..)   •  Recent  task  switcher  shows  the  recent  tasks..  
    • Tasks  
    • AcDvity  and  Tasks  
    • Reusing  AcDviDes  
    • AcDvity  Lifecycle  
    • AcDvity  Lifecycle:  States   •  Resumed   –  App  is  in  foreground  and  user  can  interact  with  it   •  Paused   –  ParDally  obscure  by  another  acDvity.     •  Stopped   –  not  visible,  in  background.  All  member  variables  are   retained,  cannot  execute  code.     •  Other  states   –  Created  and  Started  –  system  quickly  moves  from   them  to  the  next  state!  
    • public class Activity extends ApplicationContext { protected void onCreate(Bundle savedInstanceState); protected void onStart(); protected void onRestart(); protected void onResume(); protected void onPause(); protected void onStop(); protected void onDestroy(); } // The derived class must invoke these: super.onCreate(…), // super.onStart()..
    • •  onCreate() –  Create  the  user  interface   •  onStart() –  When  visible  to  user   •  onResume() –  AcDvity  is  visible  again,  iniDalize  fields,  register  listeners,   bind  to  services   •  onPause() –  AcDvity  sDll  parDally  visible,  but  most  oen  is  an  indicaDon   that  the  user  is  leaving  the  acDvity  and  it  will  soon  enter   the  stopped  state.  Release  resources,  save  app  data,   unregister  listeners,  unbind  services   •  onStop() –  AcDvity  is  no  longer  visible  to  user.  Time  or  CPU  intensive   shut-­‐down  operaDons  like  wriDng  informaDon  to  database    
    • "Importance  Hierarchy"   •  Foreground  Process  –  killed  only  as  last  resort   •  Visible  Process  –  killed  only  if  keep   foreground  processes  alive   •  Service  Process  –  killed  only  if  memory  is   needed  for  foreground  and  visible  processes   •  Background  Process  –  When  task  is  not  visible   to  user  
    • // ACTIVITY 1 public class Activity1 extends Activity implements OnClickListener { private Button changeActivity; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main1); changeActivity = (Button) findViewById(R.id.Button01); changeActivity.setOnClickListener(this); } @Override public void onClick(View v) { Intent intent = new Intent(this, Activity2.class); startActivity(intent); } }
    • // AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="fi.tamk" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".Activity1" android:label="@string/activity1"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".Activity2" android:label="@string/activity2" /> </application> <uses-sdk android:minSdkVersion="8" /> </manifest>
    • How  to  Store  State  InformaDon   •  Store  state:   – onSaveInstanceState(Bundle) •  Read  state   – onRestoreInstanceState(Bundle) •  This  will  store  data  only  temporarily:  for  app   life9me!   •  Data  will  be  held  in  memory  un9l  the  app  is   closed!  
    • Store   @Override public void onSaveInstanceState(Bundle savedInstanceState) { String text = textfield.getText().toString(); savedInstanceState.putString("someKey", text); super.onSaveInstanceState(savedInstanceState); }
    • Load   @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); if (savedInstanceState != null) { String strValue = savedInstanceState.getString("someKey"); if (strValue != null) { textfield.setText(strValue); } } }
    • INTENTS  
    • Intro  to  Intents   •  Intents  are  message-­‐passing  mechanism  that   lets  you  declare  your  intentaDon  than  an   acDon  be  performed  wit  a  parDcular  piece  of   data   •  InteracDon  between  any  android  component   •  Uses   – Start  new  acDviDes   – Broadcast  messages   – Start  new  services  
    • Intents  and  Intents  Filter   •  Intents  can  be  used  to   –  start  acDviDes  and  services   –  broadcast  data  between  components   •  Intent   –  Message  to  someone   –  Request  an  acDon  to  be  performed   –  InteracDon  between  any  app  component  on  Android   •  Intent  Filter     –  Who  can  handle  the  message?   –  Register  AcDvity,  Service  and  Broadcast  receiver  
    • Explicit  vs  Implicit  Intents   •  Explicit   – Open  explicitly  certain  AcDvity   – Internal  messaging  between  your  app   – Designated  target  class   •  Implicit   – External  messaging  between  apps   – Open  some  AcDvity  with  certain  service     •  you  don’t  know  which  acDvity  of  which  app…  
    • Explicit  Intent   // This is done in some Activity-class: Intent intent = new Intent(this, SecondActivity.class); startActivity(intent);
    • Sending  Data   Intent intent = new Intent(this, SecondActivity.class); // Extra data is key/value pairs // Send data intent.putExtra(“key”, “value”); startActivity(intent);    
    • Receiving  the  InformaDon   public class SecondActivity extends Activity { @Override public void onCreate(Bundle bundle) { super.onCreate(bundle); setContentView(R.layout.main); Bundle extras = getIntent().getExtras(); if (extras != null){ String value1 = extras.getString("key"); } ....
    • public class GettingResultsBack extends Activity { private static final int REQUEST_CODE = 10; ... public void clickButton(View v) { if (v == settings) { Intent intent = new Intent(this, Settings.class); startActivityForResult(intent, REQUEST_CODE); } } protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_CODE) { if (resultCode == RESULT_OK) { Bundle bundle = data.getExtras(); String result = bundle.getString("somevalue"); } } } }
    • Geang  results  Back   @Override public void onBackPressed() { Intent intent = new Intent(); number = phoneNumber.getText().toString(); intent.putExtra("phonenumber", number); setResult(RESULT_OK, intent); super.onBackPressed(); }
    • Implicit  Intents   •  Implicit  Intents  are  mechanism  that  lets  open   anonymous  applicaDon’s  components   •  Android  will  at  run  Dme  resolve  the  best  class   suited  to  performing  the  acDon   – Your  app  will  use  other  app’s  funcDonality  without   knowing  exactly  which  applicaDon!   •  Various  na9ve  apps  provide  components  that   can  be  called  implicitly  
    • Implicit  Intent’s  Pieces   •  Primary  pieces  of  informaDon  in  Intent’s  are   1.  Ac9on   •  The  general  acDon  to  be  performed,  for  example   ACTION_DIAL,  ACTION_VIEW   2.  Data   •  The  data  to  operate  on  expressed  in  Uri   •  Example  acDon/data  pairs   –  ACTION_VIEW,  content://contacts/people/1   –  ACTION_VIEW,  content://contacts/people/   –  ACTION_DIAL,  tel://123456   •  I  want  to  view  (ac&on)  a  webpage  (URI)    
    • Using  Implicit  Intents   Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:123456")); startActivity(intent); Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://.."); startActivity(intent); Intent  Filter's   name   Data  
    • Lot  of  NaDve  Android  AcDons   •  All  the  String  constants  can  be  found  from  Intent  class.  These  are  naDve   acDons.   •  AcDvity   –  ACTION_ANSWER    (=“android.intent.acDon.ANSWER”)   –  ACTION_CALL   –  ACTION_BUG_REPORT   –  ACTION_POWER_USAGE_SUMMARY   –  …   •  Broadcast   –  ACTION_BATTERY_CHANGED   –  ACTION_BATTERY_LOW   –  ACTION_BOOT_COMPLETED   –  ACTION_AIRPLANE_MODE_CHANGED   –  ACTION_CAMERA_BUTTON   –  ...  
    • Demo  
    • case R.id.button1: intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.tamk.fi")); startActivity(intent); break; case R.id.button2: intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:(+358)12345789")); startActivity(intent); break; case R.id.button3: intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:(+358)12345789")); startActivity(intent); break; case R.id.button4: intent = new Intent(Intent.ACTION_VIEW, Uri.parse("geo:60.123,60.1434?z=19")); startActivity(intent); break; case R.id.button5: intent = new Intent(Intent.ACTION_VIEW, Uri.parse("geo:0,0?q=kauppakadun rauta")); startActivity(intent); break; case R.id.button6: intent = new Intent("android.media.action.IMAGE_CAPTURE"); startActivityForResult(intent, 0); break; case R.id.button7: intent = new Intent(Intent.ACTION_VIEW, Uri.parse("content://contacts/people/")); startActivity(intent); break; case R.id.button8: intent = new Intent(Intent.ACTION_EDIT, Uri.parse("content://contacts/people/1")); startActivity(intent); break;
    • Intent  Filters   •  How  does  Android  know  which  applicaDon   (and  component)  handles  the  request?   •  Intent  Filters  are  used  to  register  components   as  being  capable  of  performing  an  acDon  on   parDcular  kind  of  data   – Tell  Android  that  your  app  can  service  request   from  other  apps   •  How?  Use  applicaDon’s  manifest  file  and  add   inter-filter  tag  
    • Using  Intent  Filter   •  Intent  ac9on   – Name  of  the  acDon  being  serviced.  Should  be   unique,  so  use  Java  package  naming  convenDons   •  Intent  type  /  data   – type  of  data  given  to  component  (MIME  type)   •  Intent  category   – AddiDonal  info  about  the  component  that  should   handle  the  acDon.  CATEGORY_BROWSABLE,   CATEGORY_PREFERENCES...  
    • ImplemenDng  Own  Intent  Filter   <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="fi.pohjolainenconsulting.demos" android:versionCode="1" android:versionName="1.0"> <uses-sdk android:minSdkVersion="8" /> <uses-permission android:name="android.permission.INTERNET"></uses-permission> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".PlaySound" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> <intent-filter> <action android:name="fi.pohjolainenconsulting.demos.PLAYSOUND" /> <data android:scheme="http" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> </application> </manifest>
    • Opening  the  AcDvity  (App  A)   intent = new Intent("fi.pohjolainenconsulting.demos.PLAYSOUND", Uri.parse("http://www….fi/music.mp3")); startActivity(intent);
    • The  AcDvity  (App  B)   public class PlaySound extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Intent i = getIntent(); Uri uri = i.getData(); if(uri != null) { MediaPlayer mp = MediaPlayer.create(this, i.getData()); mp.start(); } } }
    • ImplemenDng  a  Browser   <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="fi.pohjolainenconsulting.mybrowser" android:versionCode="1" android:versionName="1.0"> <uses-sdk android:minSdkVersion="8" /> <application android:icon="@drawable/icon" android:label="@string/ app_name"> <activity android:name=".MyBrowser" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <data android:scheme="http"/> </intent-filter> </activity> </application> <uses-permission android:name="android.permission.INTERNET"></uses- permission> </manifest>
    • ApplicaDon  Components   1.   AcDviDes  and  Intents   2.  Services   3.  Broadcast  receivers   4.  Content  provides  
    • 2.  Services   •  A  facility  for  the  applicaDon  to  tell  the  system   about  something  it  wants  to  be  doing  in  the   background   •  Background  music,  fetching  data  over  network..   •  AcDvity  is  frozen  when  user  moves  to  another   AcDvity.  Service  can  go  on  in  the  background.   •  Subclass  of  Service –  AcDvity:  User  chooses  a  song   –  Service:  Song  is  played   •  OPen  runs  in  separate  thread  
    • About  Services   •  Service  is  NOT  a  separate  process  or  thread   •  Provides  two  features   –  Tell  the  system,  that  we  want  to  do  something  in  the   background.  (startService())     •  Even  if  the  app  closes!   –  The  ability  to  expose  funcDonality  to  other  apps   (bindService())   •  Service  is  a  simple  class,  you  must  implement   separate  threads  by  yourself.   •  Modify  the  Manifest  –  file!  
    • public class MyService extends Service { @Override public IBinder onBind(Intent arg0) { // TODO Auto-generated method stub return null; } @Override public void onDestroy() { Log.d("MyService", "onDestroy()"); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.d("MyService", "onStart()"); // START_STICKY: If Service is killed try to restart it return START_STICKY; } @Override public void onCreate() { Log.d("MyService", "onCreate()"); } }
    • public class MainActivity extends Activity implements OnClickListener{ private Button startService; private Button stopService; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState, "MainActivity"); setContentView(R.layout.main); startService = (Button) findViewById(R.id.Button02); stopService = (Button) findViewById(R.id.Button03); startService.setOnClickListener(this); stopService.setOnClickListener(this); } @Override public void onClick(View v) { if (v == startService) { Intent intent = new Intent(this, MyService.class); startService(intent); } else if (v == stopService) { Intent intent = new Intent(this, MyService.class); stopService(intent); } } }
    • public class MyService extends Service implements Runnable { private boolean isRunning; private final static String TAG = "MyService"; private Thread thread; @Override public IBinder onBind(Intent arg0) { // TODO Auto-generated method stub return null; } @Override public void onDestroy() { isRunning = false; } @Override public void public int onStartCommand(Intent intent, int flags, int startId) { if(!isRunning) thread.start(); return START_STICKY; } @Override public void onCreate() { isRunning = false; thread = new Thread(this); } @Override public void run() { isRunning = true; while(isRunning) { try {                                                                            Log.d(TAG,  "Service  running...");   Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }
    • <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="fi.tamk" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".CallMe" 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="8" /> </manifest>
    • About  Bound  Services   •  Problem:  Ac9vity  can  only  start  and  stop  the   service   •  SoluDon:  create  bound  service:   –  Interact  with  the  service  from  acDviDes  or  other   components   –  Expose  some  of  app’s  funcDonality  to  other  apps  (IPC)   •  To  create  bound  service,  implement  onBind() •  A  bound  service  typically  lives  only  while  it  serves   another  applicaDon  component  and  does  not  run   in  the  background  indefinitely  
    • Lifecycle  
    • CreaDng  a  Bound  Service   •  1.  Private  Service  for  your  own  app   –  Extend  Binder  class   –  Example:  music  applicaDon  that  needs  to  bind  an   acDvity  to  its  own  service  that's  playing  music  in  the   background.   –  Service  must  be  in  the  same  process  than  acDvity   –  Recommended  for  acDviDes  which  need  to  have  fast   communicaDon  with  the  service   •  2.  Service  for  other  apps  (work  across  processes)   –  Use  a  Messenger  
    • Private  Service:  Extending  Binder   •  If  your  service  is  private  to  your  app,  you  can   use  Binder •  Binder?  Defines  programming  interface  that   clients  can  use   •  Binder  can   – Contain  public  method  that  the  client  can  call   – Return  the  Service  object  itself,  so  all  the  public   methods  from  the  service  is  available  
    • How?   •  Service   – Create  the  Binder  object  in  your  Service   – Return  the  object  in  onBind()  method   •  Client   – Receive  Binder  object  from  onServiceConnected   -­‐  method  
    • Local  Service  (Same  Process)   public class MyService extends Service { private IBinder mBinder; public void onCreate() { Log.d("MyService", "onCreate()"); // LocalBinder is my class which extends Binder // that implements IBinder mBinder = new LocalBinder(this); } public IBinder onBind(Intent intent) { // Returns IBinder, which "wraps" MyService inside! return mBinder; } public void onDestroy() { Log.d("MyService", "onDestroy()"); } public int onStartCommand(Intent intent, int flags, int startId) { Log.d("MyService", "onStart()"); return START_STICKY; } // Method for clients! public void someMethod() { Toast.makeText(this, "someMethod is called!", Toast.LENGTH_LONG).show(); } } public class LocalBinder extends Binder { private MyService myservice; public LocalBinder(MyService ref) { myservice = ref; } public MyService getService() { return myservice; } }
    • Client   •  Client  can  bind  to  service  by  calling   bindService() •  bindService() –  method  needs   ServiceConnection  object,  which  monitors   the  connecDon  of  the  service   •  bindService() returns  immediately,  but   ServiceConnecDon’s  onServiceConnected  is   called  to  deliver  the  Binder  to  the  client  
    •  Client  (Same  Process)   public class LocalServiceExample extends Activity { // My bounded local service private MyService mBoundService; // This will monitor the connection to the service private MyServiceConnection mConnection; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // Creating the connection mConnection = new MyServiceConnection(); // Binding the service // This will return immediately, but // onServiceConnected is called // to deliver the Binder to the client bindService(new Intent(this, MyService.class), mConnection, Context.BIND_AUTO_CREATE); } // This is a helper class that monitors the connection public class MyServiceConnection implements ServiceConnection { @Override public void onServiceConnected(ComponentName className, IBinder service) { mBoundService = ((LocalBinder) service).getService(); } @Override public void onServiceDisconnected(ComponentName arg0) { mBoundService = null; } } void doUnbindService() { unbindService(mConnection); } protected void onDestroy() { super.onDestroy(); doUnbindService(); } public void click(View v) { // We are now able to call other methods from the service! mBoundService.someMethod(); } }
    • Remote  Processes:  Messenger   •  Use  Messenger   –  Service  implements  Handler  that  receives  a  callback  for   each  call  from  client   –  The  Handler  is  used  to  create  Messenger   –  Messenger  creates  IBinder  object  that  the  service  returns   –  Clients  use  the  IBinder  to  instanDate  the  Messenger.   Clients  send  messages  to  the  service   –  The  service  receives  the  messages   •  See  example:     –  http://www.techotopia.com/index.php/ Android_Remote_Bound_Services_ %E2%80%93_A_Worked_Example
    • ApplicaDon  Components   1.   AcDviDes   2.  Services   3.  Broadcast  receivers   4.  Content  provides  
    • 3.  Broadcast  Receivers   •  A  broadcast  receiver  is  a  component  that  does   nothing  but  receive  and  react  to  broadcast   announcements   •  Your  app  can   –  1)  Receive  and  react  to  system  services  (example:   banery  low)   –  2)  Receive  and  react  to  other  apps  broadcast   announcements     –  3)  IniDate  broadcasts  to  other  apps   •  App  is  given  fixed  amount  of  Dme  to  react  on  the   broadcast!  (10  secs!)  
    • MyBroadCastReceiver   BroadCastReceiver   onReceive(..)   Some   System  Service   broadcast  message   register  
    • Registering   •  To  register  Broadcast  Receiver,  you  can   – 1)  Dynamically  register  with  registerReceiver   (in  code)   – 2)  StaDcally  public  receiver  and  <register> tag   in  AndroidManifest.xml •  Note:  if  you  are  doing  this  dynamically  and   you  are  working  in  local,  you  don't  have   modify  manifest  –  file.  
    • 1.  Registering  in  Code   public class Main extends Activity { MyBroadCastReceiver s; IntentFilter filter; @Override public void onResume() { super.onResume(); filter = new IntentFilter("android.intent.action.TIME_TICK"); s = new MyBroadCastReceiver(); registerReceiver(s, filter); } @Override public void onPause() { super.onPause(); unregisterReceiver(s); } }
    • BroadcastReceiver   import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; public class MyBroadCastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Log.d("IncomingReceiver", "Time Tick"); } }
    • 2.  Registering  Broadcast  Receiver  in  Manifest   <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="fi.tamk" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".Main" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <receiver android:name=".MyBroadCastReceiver" android:enabled="true"> <intent-filter> <action android:name="android.intent.action.TIME_TICK" /> </intent-filter> </receiver> </application> <uses-sdk android:minSdkVersion="8" /> </manifest>
    • Sending  Broadcast   •  Broadcast  is  sent  using  Intent  and   sendBroadcast  or  sendOrderedBroadcast   methods   •  Example:   Intent intent = new Intent("fi.tamk.DETECTION"); sendBroadcast(intent);
    • Normal  vs.  Ordered  Broadcast   •  Normal  Broadcasts   – Sent  with  sendBroadcast.  All  broadcasts  are  run   in  undefined  order,  oen  at  the  same  Dme.   •  Ordered  Broadcasts   – Sent  with  sendOrderedBroadcast.  Each  receiver   executes  in  turn.  Possible  to  propagate  a  result  to   next  receiver.  Order  can  be  controlled  using   android:priority  tag.  
    • Receiver  Lifecycle   •  Broadcast  Receiver  object  is  valid  only  for  the   dura&on  of  the  onReceive(Context,  Intent)   method   – Before  API  Level  11:   •  You  cannot  do  anything  asynchronous  in  here!   – Aer  API  level  11  (3.0  -­‐>)   •  You  can  use  method  goAsync()  to  create   asynchronous  processing.    See:   •  hnp://justanapplicaDon.wordpress.com/tag/goasync/   – You  can  always  start  a  service    
    • Registering  Broadcast  Receiver  in  Java   public class Main extends Activity implements OnClickListener { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Button click = new Button(this); click.setText("Click me!"); setContentView(click); click.setOnClickListener(this); // Registering MyBroadCastReceiver to receive Broadcasts IntentFilter filter = new IntentFilter("fi.tamk.DETECTION"); MyBroadCastReceiver s = new MyBroadCastReceiver(); registerReceiver(s, filter); } @Override public void onClick(View v) { // Sending Broadcast Intent intent = new Intent("fi.tamk.DETECTION"); sendBroadcast(intent); } }
    • Registering  Broadcast  Receiver  in  Manifest   <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="fi.tamk" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".Main" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <receiver android:name=".MyBroadCastReceiver" android:enabled="true"> <intent-filter> <action android:name="fi.tamk.DETECTION" /> </intent-filter> </receiver> </application> <uses-sdk android:minSdkVersion="8" /> </manifest>
    • ApplicaDon  Components   1.   AcDviDes   2.  Services   3.  Broadcast  receivers   4.  Content  provides  
    • 4.  Content  Providers   •  A  content  provider  makes  a  specific  set  of  the   applica&on's  data  available  to  other  applica&ons   •  =>  Share  data  to  other  apps   •  Any  app  with  appropriate  permission,  can  read   and  write  the  data.   •  Many  naDve  databases  are  available  via  the   content  providers,  for  example  Contact  Manager   •  Files,  SQL  database   •  Common  interface  for  querying  the  data  
    • About  Content  Provides   •  The  result  of  the  query:  simple  table  in  Query   object   •  Content  provider  exposes  a  public  URI  that   uniquely  idenDfies  its  data  set   – URIs  begin  with  content:// – Android  provides  constants  for  naDve  content   providers,  for  example:   •  ContactsContract.Contacts.CONTENT_URI
    • Querying  Na9ve  Content  Provider   •  You  need   – URI   •  ContactsContract.Contacts.CONTENT_URI – Names  of  data  fields  (result  comes  in  table)   •  ContactsContract.Contacts.DISPLAY_NAME – Data  types  of  those  fields   •  String •  Remember  to  modify  the  manifest  file  for   permissions!  
    • Query   Cursor cur = managedQuery(ContactsContract.Contacts.CONTENT_URI, // What Content Provider null, // Which columns to return (all columns) null, // Which rows to return (all rows) null, // Selection arguments (none) null); // In what order if (cur.moveToFirst()) { // Get column DISPLAY_NAME int nameColumn = cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME); do { // Get the field values String name = cur.getString(nameColumn); System.out.println(name); } while (cur.moveToNext()); }
    • Modifying  the  Manifest   <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="fi.tamk" android:versionCode="1" android:versionName="1.0"> ... <uses-permission android:name="android.permission.READ_CONTACTS"> </uses-permission> </manifest>
    • ImplemenDng  your  own  Content  Provider   1.  Set  up  a  system  for  storing  data   For  example,  SQLite  or  flat  file   2.  Extend  ContentProvider  class   3.  Declare  the  Content  Provider  in  manifest  
    • 2.  Extend  Content  Provider   public class MyContentProvider extends ContentProvider { public static final Uri CONTENT_URI = Uri.parse("content://fi.tamk.phonenumber"); @Override public int delete(Uri uri, String selection, String[] selectionArgs) {...} @Override public String getType(Uri uri) {...} @Override public Uri insert(Uri uri, ContentValues values) {...} @Override public boolean onCreate() {...} @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {...} @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {...} }
    • 3.  Manifest   <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="fi.tamk" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".CallMe" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <provider android:name=".MyContentProvider" android:authorities="fi.tamk.phonenumber"></provider> </application> <uses-sdk android:minSdkVersion="8" /> </manifest>
    • Querying  the  Content  Provider   •  NaDve  Content  Provider   –   Cursor cur = managedQuery(ContactsContract.Contacts.CO NTENT_URI, null, null, null, null); •  My  own  provider   – Cursor cur = managedQuery(MyContentProvider.CONTENT_UR I, null, null, null, null);