Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Dori waldman android _course


Published on

Android course for developers from beginner to expert

Published in: Technology
  • Be the first to comment

Dori waldman android _course

  1. 1. Android Development Dori Waldman
  2. 2. Overview  Android Introduction  Android Components (Activity, Intent, Fragment, Service, Broadcast receiver,  Working with Resources  Application Lifecycle (Activity,Service,Fragment)  Working with Threads  Service (local vs remote)  Persistence  Location  Http/WS connection  Security / permission model  Hybrid development (phonegap/jquery mobile)  Development/Test tools ()  Native UI components (Toast…Widget) 2 ContentProvider…)
  3. 3. Android Introduction
  4. 4. Course Resources 4
  5. 5. Introduction • • 5 In 2005 Google acquired startup company called “Android” and released the code as an open source. In late 2007, Android become the chosen OS by industry leaders such as : Sprint, T-Mobile, Samsung, Toshiba Native OS
  6. 6. Smart Phone definition ? • • 6 No standard (screen resolution / camera / GPS) More than 30 vendors (HTC, Samsung , Firefox …)
  7. 7. Code Complicity if (packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA)) { Log.i("camera", "This device has camera!"); }else{ Log.i("camera", "This device has no camera!"); } if ( android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD) { // only for gingerbread and newer versions } GooglePlayServicesUtil.isGooglePlayServicesAvailable() 7
  8. 8. The Pain of Native UI , or why Hybrid is poplar ? Same App on different devices/OS 2.3.4 Samsung 8 4.1 Samsung
  9. 9. Mobile Web Vs Desktop Web • 9 Web site should fit both – one development effort
  10. 10. Mobile Web Vs. Desktop Web • Same functionality ? No uploads View pictures taken nearby 10
  11. 11. Mobile Challenges (external app events) • • Android OS might kill the application process in case of non efficient resources therefore developer should listen to OS events (onLowMemory() …) and response to them (save the application data). For example • phone call during payment flow. • device rotation – will restart the application • lost internet connection during upload. 11
  12. 12. Major Android versions • • • 12 2.3 -API Level: 9 (gingerbread) 3.0 -API Level: 11 (honeycomb) provide support for tablets 4.0 -API Level: 14 (ice cream sandwich)
  13. 13. OS learning curve : Its not just New OS version , • New Features  • Code is changing quickly  • Between android 2-4 the way that we invoke background threads has been changed 4 times • Map Api has been changed dramatically between version 1 and version 2 Those changes are not cosmetic, they allows to create better application: save battery, avoid application crash. 13
  14. 14. Android is not only for Phones/Tablet/Tv 14
  15. 15. Android Stack
  16. 16. Stack Linux Kernel provides hardware drivers, memory/power/network/security/thread management 16
  17. 17. File System • User application will be located under data folder • Framework Application will be located under System/App folder • C++ libs will be located under system/framework folder 17
  18. 18. NDK • Allows to develop parts of the application using native-code languages such as C and C++ • • Android C++ framework: – – 18
  19. 19. Android Artifact • Android executable “.apk” file (similar to war file). • Each app run in its own linux process • Java classes are being convert into Dalvik executable “.dex” file (corresponding to .jar file) which are half size compare to jar file. • 19 Reverse engineering : apk  dex  *.class files  java • • •
  20. 20. Android Tools • AVD (create an run emulator) • DDMS (monitor device/emulator) • ADB (control device from CMD) • Logcat • AAPT (Android Asset Packaging Tool - create apk) • SQLLite3 • TraceView/dmtracedump (analyze logs) • ProGuard (shrink artifacts size) • Monkey/MonkeyRunner – API to remote control device (automate test) • Draw9Patch (utility to create scalable bitmap) , Pixel Perfect • Lint (tool to app optimization) • Hierarchy viewer / uiAutomatorViewer • DX (convert java to dex) • Mksdcard (external storage for emulator) 20 • Hprof-conv (convert logs to preferred profile tool)
  21. 21. Main Components Activity – Manage the business logic, UI flow, events and invoke services Fragment – embedded inside activity, allows reusable UI elements Service - background process, which has no user interface, used for long running operation and also to expose functionality for external applications. Content Provider - used to share data among applications without exposing the data layer (for example retrieve contact list from database) Broadcast – used to send events Intent - used to invoke activity/service/broadcast -----------------------------------------------------------------------------------------------------------------------View – UI component (Button, Text area …) Layout – Composite View 21
  22. 22. First App
  23. 23. Recommended way to develop UI 23
  24. 24. Build UI (Code / XML) <LinearLayout xmlns:android= android:orientation="vertical" android:layout_width="fill_parent“ android:layout_height="fill_parent"> <TextView android:text="@string/InsertName" android:id="@+id/textView1“ android:layout_width="wrap_content" android:layout_height="wrap_content"> </TextView> <Button android:text="Button" android:id="@+id/button1“ android:layout_width="wrap_content" android:layout_height="wrap_content"> </Button> </LinearLayout> LinearLayout linearLayout = new LinearLayout(this); Button button = new Button(this); linearLayout.addView(button); setContentView(linearLayout); 24
  25. 25. Code Example • EX1 – Create Application with 3 activities , 2 fragments – Transfer data between activities using Intent / StartActivityForResult – Transfer data between activity and its fragments using getActivity() – Build UI programmatically/xml – Using Shared Preferences to persist and transfer data – Fragment Stack – Activity Stack – Open Activity Explicitly / Implicitly 25
  26. 26. Activity
  27. 27. Activity (Activity Stack) • Activity class takes care of creating a window for you in which you can place your UI and interact with the user. • One application contains several activities which are managed in stack • Activity is a single, focused thing that the user can do, for example one activity will show contact list, another activity will invoke a call to selected contact. 27
  28. 28. Activity State: • Active - The screen is foreground/focus • Pause - lost focus but is still visible (another activity has focus on top of this activity), it maintains its state and remains attached to the window manager, but can be killed by the system in extreme low memory situations. • Stop – Not visible to the user (cover by another activity) It still retains its state, it will often be killed by the system when memory is needed elsewhere. • Finish – either by calling to finish() or when OS kill the process, When application finished, it is actually cached until OS will free cached resources 28
  29. 29. Activity Lifecycle onRestoreInstanceState onSaveInstanceState The entire lifetime happens between onCreate() – onDestroy() The visible lifetime happens between onStart() - onStop(). The foreground lifetime (focus) happens between onResume() - onPause() 29
  30. 30. Activity Lifecycle - entire lifetime onCreate() is called only once when the activity is created (~Constructor), use this method for: • Initialize UI elements (findViewById(), setContentView(int) ), • initialize resources (avoid the creation of short-term objects in several places)... onCreate() /onRestoreInstanceState() methods are also used to restore UI state (if exist) onDestroy() is called either because the activity is finishing (finish()) , or because the OS destroying this instance of the activity to free resources (When OS kill the application this step might not be invoked at all). Use onDestroy() to clean up any resources which has been established in onCreate() like close network/database connections. 30
  31. 31. Activity Lifecycle - visible lifetime During this phase the user can see the activity on-screen, but its not at foreground/focus and there is no interacting with the user. The onStart() and onStop() methods can be called multiple times, as the activity get/lose focus. onStart() is called after onCreate, or after onRestart() (when user navigate back to the activity) onStop() is called when the activity becomes invisible to the user. Use this method to : Suspend all resources which are being used to update the user interface as in this phase the activity is not visible to the user For example suspend threads, stop animation, unregister to Broadcast Receivers, stop GPS, unbind services… 31
  32. 32. Activity Lifecycle – foreground/focus lifetime During this phase the Activity is in focus and user interact with it. Activity can frequently go between the OnResume() and onPause() states (device went to sleep) therefore code between these methods should be kept lightweight. OnResume() At this point activity is at the top of the activity stack. onPause() will be invoked when activity is not in focused, • It‟s the last safe point, after this point Activity may be killed without continue to onStop() therefore you should use this point to persist user changes. From onPause() , either OnResume() or onStop() will be invoked. 32
  33. 33. OnSaveInstanceSave()– onRestoreInstanceState() • OS default behavior save the state of an activity in memory when it is stopped. This way, when users navigate back to a previous activity, the view appears the same way the user left it. • The default implementation calls the corresponding onSaveInstanceState() method for every View in the layout (only if for views with android unique id) and saves the views state in Bundle : onCreate(Bundle) /onRestoreInstanceState(Bundle) • For all other cases you need to save and restore the UI state via onSaveInstanceState() • onRestoreInstanceState(Bundle) will be called by OS only if OS killed the application and restart it again. 33
  34. 34. Activity A Start INFO/EX1-A (406): onCreate Begin INFO/EX1-A (406): onCreate End INFO/EX1-A (406): onStart Begin INFO/EX1-A (406): onStart End INFO/EX1-A (406): onResume Begin INFO/EX1-A (406): onResume End Example of Activity lifecycle – Demo EX1 Click on a button And open activity B click on “Close“ and return to First Activity 34 INFO/EX1-A (406): onSaveInstanceState Begin INFO/EX1-A (406): onSaveInstanceState End INFO/EX1-A (406): onPause Begin INFO/EX1-A (406): onPause End INFO/EX1-B (406): onCreate Begin INFO/EX1-B (406): onCreate End INFO/EX1-B (406): onStart Begin INFO/EX1-B (406): onStart End INFO/EX1-B (406): onResume Begin INFO/EX1-B (406): onResume End INFO/EX1-A (406): onStop Begin INFO/EX1-A (406): onStop End INFO/EX1-B (406): onPause Begin INFO/EX1-B (406): onPause End INFO/EX1-A (406): onRestart Begin INFO/EX1-A (406): onRestart End INFO/EX1-A (406): onStart Begin INFO/EX1-A (406): onStart End INFO/EX1-A (406): onResume Begin INFO/EX1-A (406): onResume End INFO/EX1-B (406): onStop Begin INFO/EX1-B (406): onStop End INFO/EX1-B (406): onDestroy Begin INFO/EX1-B (406): onDestroy End
  35. 35. Activity „A‟ started Example of Activity lifecycle (Ex1) Get phone call, OS Destroy the Activity Hung up and unlock Phone, back to app 35 INFO/EX1-A (406): onCreate Begin INFO/EX1-A (406): onCreate End INFO/EX1-A (406): onStart Begin INFO/EX1-A (406): onStart End INFO/EX1-A (406): onResume Begin INFO/EX1-A (406): onResume End INFO/EX1-A (406): onSaveInstanceState Begin INFO/EX1-A (406): onSaveInstanceState End INFO/EX1-A (406): onPause Begin INFO/EX1-A (406): onPause End INFO/EX1-A (406): onStop Begin INFO/EX1-A (406): onStop End INFO/EX1-A (406): onRestart Begin INFO/EX1-A (406): onRestart End INFO/EX1-A (406): onStart Begin INFO/EX1-A (406): onStart End INFO/EX1-A (406): onResume Begin INFO/EX1-A (406): onResume End INFO/EX1-A (832): onCreate Begin INFO/EX1-A (832): onCreate End INFO/EX1-A (832): onStart Begin INFO/EX1-A (832): onStart End INFO/EX1-A (832): onRestoreInstanceState Begin INFO/EX1-A (832): onRestoreInstanceState End INFO/EX1-A (832): onResume Begin INFO/EX1-A (832): onResume End
  36. 36. Activity Configuration *configChanges attribute prevent application from restart (rotate) opics/manifest/activity-element.html 36
  37. 37. Task – Task Stack (Home Button) • Task is a collection of activities that users interact with when performing a certain job (~application) • When the user leaves a task by pressing the Home button, the current activity is stopped and its task goes into the background. • The OS retains the state of every activity in the task. If the user later on resumes the task by selecting the launcher icon that began the task, the task comes to the foreground and resumes the activity at the top of the stack. • For example open SMS app and write SMS , Click on Home button and start another app, close that app , long click on Home button and select the SMS app , you will see the text that you started to wrote. Task B receives user interaction in the foreground, while Task A is in the background, waiting to be resumed. 37
  38. 38. Fragment
  39. 39. Fragment • Divide Activity to reusable components, each has its own lifecycle (onCreate()…) • Fragment is tightly coupled to activity in which its placed, therefore when the activity is stop/pause/destroy the fragments are also stop/pause/destroy. • Fragments are also managed in a stack • Fragment can be added/removed several time during activity lifetime • Its possible to create without any UI • For backward compatibility you should extends “FragmentActivity” instead of Fragment” 39
  40. 40. Fragment Lifecycle OnAttach – bound to activity , get reference to parent activity onCreate – initialize fragment resources not UI ! onCreateView – initialize fragment UI (like activity onCreate) onActivityCreated – a callback that parent activity is ready , incase the fragment UI depend on parent activity UI, use to initialize Frag UI here onStart – visible onResume – focus onPause – end of focus onSavedInstanceState onStop – end of visible onDestroyView – Fragment View is detached , clean UI resources onDestroy – clean resources , end of life onDetach – Fragment is detach from activity, if parent activity will be killed, this step will not be called 40
  41. 41. Static way to add fragment <linearLayout> <!– FragA is a class that extends Fragment - -> <fragment android:name=“com.dori.FragA”/> </linearLayout> 41
  42. 42. Dynamic way to add fragment (Frag container) <linearLayout> <FrameLayout android:id=“FragContainer” /> </linearLayout> FragmentTransaction ft = fragmentManager.beginTransaction(); Fragment frag = Ft.findFragmentById( FragContainer) ft.remove(frag); ft.add( FragContainer, MyFragB); ft.addToBackStack(“tag”); ft.commit(); 42
  43. 43. Fragments for both Tablet / Phones • Each activity will convert into fragment meaning: – Create new fragments and move the activities code into it , the original activity will act as a container for the fragment. • Create 2 kinds of layouts, the OS will select the layout according to screen size. – One layout in layout-land folder for tablet view with fragA_layout.xml – layout per fragment fragA_layout.xml and fragB_layout.xml • Each fragment will be created in a separated activity , Activity B is never used on a tablet. It is simply a container to present Fragment B. • When you need to switch Fragments, activity A checks if the second fragment layout is available in his layout: – If the second fragment is there, activity A tells the fragment that it should update itself. – If the second fragment is not available activity A starts the second activity. 43
  44. 44. Work with Fragments 44
  45. 45. Work with Fragments • working with fragments • • 45
  46. 46. Fragment recreation • When activity is being destroyed and restart (Rotate) you can select that the fragment will not be restart with its associate activity, by calling setRetainInstane(true) from the Fragment onCreate() • In that case The Fragment onDestroy() onCreate() will not be called while the attached activity is being destroyed-created , All other Fragment lifecycle methods will be invoked like onAttach…., therefore moving most of the object creation to onCreate will improve the performance 46
  47. 47. Intent
  48. 48. Intent • Intent is used to invoke activity/service/broadcast – More Intents components will be explained later: • PendingIntent • ServiceIntent • Broadcast Intents • There are 3 ways to invoke activity: Intent intent = new Intent(MyActivity.this, AnotherActivity.class); Intent.putExtra(“someLabel”, “someValue”); startActivity(intent); 48
  49. 49. Second way to invoke Intent: Intent intent = new Intent(); intent.setComponent( new ComponentName( "“, "“ ); startActivity(intent) 49
  50. 50. Third way to invoke intent - Late Runtime Binding This example will start dialer activity and will make a call Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(“tel:52325”)); startActivity(intent); Action Data -optional While this intent will only open dialer application new Intent(Intent.ACTION_DIAL); Late Runtime Binding means that Android at run time resolve the class that will perform the action, it can be different class deepened on the type of data specified (will be explained later) 50
  51. 51. Activity Callback: • In order to get response back from sub activity, invoke startActivityForResult and provide activity Id: Intent intent = new Intent(this, SubAct.class); Int subActId = 1; startActivityForResult(intent, subActId ); • Before sub-Activity is closed, call setResult to return a result(as intent) with status to the calling Activity. Intent myIntent= new Intent(); myIntent.putExtra("somethingBack",”someValue”); setResult(RESULT_OK, myIntent); finish(); 51
  52. 52. Activity Callback: • When a sub-Activity closes, callback method will be invoked in the parent activity onActivityResult public void onActivityResult(int requestCode,int resultCode,Intent data) { switch(requestCode) { case (subActId) : { if (resultCode == Activity.RESULT_OK) { data.getStringExtra(“somethingBack”) … 52
  53. 53. Logs – callback is called before activity closed • • • • • • • • • • • • 53 INFO/B (2673): onBackPressed start INFO/B (2673): saveBeforeClose begin INFO/B (2673): editText.getText()=hi INFO/B (2673): saveBeforeClose end INFO/B (2673): onBackPressed end INFO/B (2673): onPause start INFO/B (2673): onPause end INFO/A (2673): onActivityResult --- callback INFO/B (2673): onStop start INFO/B (2673): onStop End INFO/B (2673): onDestroy start INFO/B (2673): onDestroy end
  54. 54. Adding & Retrieving data from intent Intent.putExtra(String name, boolean value); //simple value Intent.putExtra(String name, int[] values); // simple array Intent.putParcelableArrayListExtra(String name, ArrayList arrayList); Intent.putExtra(Bundle bundle) // Bundle is a key-value map Intent.putSerilaizable() If you're just passing objects use Parcelable , It requires a little more effort to use than using Java's native serialization, but it's way faster (and I mean way, WAY faster). intent.getExtras(); 54
  55. 55. Intent Filters • Intent Filters are used to register Activities, Services, and Broadcast Receivers, if the intent filter attributes “match” the calling Intent (will be explained later) the action will be invoked, for Example AppA will invoke AppB: Intent intent = new Intent(“com.dori.AnotherActivity”); // Late Runtime Binding (like open camera) startActivity(intent); -------------------------------------------------------------------------------------------------<activity android:name=“SomeActivity“> // In AppB Manifest <intent-filter> <action android:name="com.dori.AnotherActivity"/> <category android:name="android.intent.category.DEFAULT" /> <data …. /> </intent-filter> </activity> -----------------------------------------------------------------------------------------55  AppB will be open and , SomeActivity will be invoked
  56. 56. How does android know which Intent to invoke ? • Android collect all the Intent Filters available from the installed apps, Intent Filters that do not match the action or category associated with the Intent being resolved are removed from the list. • If the class name attached to an intent (explicit), then every other aspect or attribute of the intent is ignored and that class will be execute, no need to continue to match the intent data. • Otherwise we need to have a full match of action+data+category 56
  57. 57. Sticky Intent A normal Broadcast intent is not available anymore after is was send and processed by the system. Android system uses sticky Broadcast Intent for certain system information like battery changes, The intent which is returned is Sticky meaning that it keep available, so clients can quickly retrieve the Intent data without having to wait for the next broadcast, the clients no need to register to all future state changes in the battery. Sticky broadcasts are used by android to send device state, they are heavy on the system , don‟t use them if you don‟t need. 57 unregister Receiver
  58. 58. Send Sticky Intent Intent intent = new Intent("some.custom.action"); intent.putExtra("some_boolean", true); sendStickyBroadcast(intent); …. removeStickyBroadcast(Intent intent) 58
  59. 59. Manifest
  60. 60. <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="" package="com.dori" android:versionCode="1“ android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".MyAct" 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:name=".MyService"></service> //Content Provider <provider android:permission=”com.paad.MY_PERMISSION” android:name=”.MyContentProvider” android:enabled=”true” android:authorities=”com.paad.myapp.MyContentProvider”/> //Broadcast reciver <receiver android:enabled=”true” android:label=”My Broadcast Receiver” android:name=”.MyBroadcastReceiver”/> //uses-permission tags declare the permissions you‟ve determined that your application needs for it to operate properly. The permissions you include will be presented to the user, to grant or deny, during installation <uses-permission android:name=”android.permission.ACCESS_LOCATION”/> // adding restrict access to an application component, Other applications will then need to include a uses-permission tag in their manifests before they can use these protected components <permission android:name=”com.paad.DETONATE_DEVICE” android:protectionLevel=”dangerous” Destruct” android:description=”@string/detonate_description”/> </application> 60 </manifest> android:label=”Self
  61. 61. Manifest (~web.xml) • • • • • • • • • 61 Uses-sdk : which android version are being supported Uses-configuration : like application require finger touch Uses-feature : hardware feature like NFC Uses-permission : security model Permission : security model Instruments : testing framework (provides hook to the tested class) Support-screens : (small …Xlarge) Used library Application (one per manifest) – Activity – Service – Content provider – Broadcast receiver
  62. 62. Application Class • One per application • Custom Application: Class MyApp extends Application{ } And in manifest : <application android:name=“.MyApp” …> Usage : focal point to handle events like onLowMemory, create HttpClient, ACRA (catch app exception) 62
  63. 63. Resource
  64. 64. Android Project Folder • Src - A folder containing application source files • Gen – Generated folder, don‟t touch. • Assets – resources which are not generating ID (will be explained later), assets directory can be used to store any kind of data. 64
  65. 65. • Res – A parent folder containing the resources of the application, most of the resources are xml descriptors files. – Values - A folder containing resources like • strings, • colors, <color name=“mycolor”>#0000000</color> • dimensions (best practice use dp or sp) <dimen name=“ex1”> 16dp </dimen> • Style – Drawable - A folder containing the images or xml image-descriptor files. – layout – In order to provide different layouts there is a need to create specific folders for each configuration – xml - A folder containing additional XML files used by the application. – raw - A folder containing non xml data like audio/video files, android compiles into binary format all the resources except the raw resources which are copied as-is into the final .apk file – Menu - A folder containing XML-descriptor files for the menus – Anim - A folder containing XML-descriptor files for the animations. 65
  66. 66. localization • Use folders to support localization, orientation …. : • reslayoutmain_layout.xml • reslayout-landmain_layout.xml • reslayout-carmain_layout.xml //docking type • resvaluesstrings.xml • resvalues-enstrings.xml 66
  67. 67. Resources per resolution/screen size Layouts: Res/layout-long-land // long screen in landscape mode Res/layout-w600dp // screen width is 600 dp Res/layout-small // before android 3.2 Images folders: Res/drawable-ldpi – low density for screen with 120dpi Res/drawable-mdpi –for screen with 120dpi Res/drawable-tvdpi –213 dpi Res/drawable-hdpi – low density for screen with 240dpi Res/drawable-xhdpi – low density for screen with 320dpi Res/drawable-nodpi – force no scale regardless the device screen size 67
  68. 68. Working with resources • Android inject the resource value at run time (in /res/values/strings.xml) <string name=“NewWindow">myText</string> (In /res/layout/main.xml) <Button android:id="@+id/button2 “ android:text="@string/NewWindow“ /> • Android generate Id for each resource in public static final int button2=0x7f060004; public static final int NewWindow=0x7f040005; • Getting resources via code(activity) Button button = (Button)findViewById( String myAppName = getResources().getString(R.string.app_name); 68
  69. 69. Resources Types: • "@+id/editText1“ : my application resource , (+) means that this is a new resource , getString(R.string. editText1) • "@android:id/button1“ , android:src="@android:drawable/star_big_on“: Android resource, getString(android.R.string. button1) • ?android – theme support like <color:textcolor=“?android:textcolor”/> 69
  70. 70. Working with Assets AssetManager used to manage “Assets” resources AssetManager am = activity.getAssets(); InputStream is ="test.txt"); 70
  71. 71. Application Meta Data Files
  72. 72. Application metadata files Both files are generated by android proguard.cfg / proguard-project.txt - Java class file shrink, optimizer – parameters like android version 72
  73. 73. Thread
  74. 74. Why Threads are important • By default the all androd components runs on the main thread (UI thread) – Activity – Service – ContentProvider – BroadcastReciver • If any action takes more than 5 seconds, Android throws an ANR message. • In order to solve this we must manage time consuming action in a separated thread 74
  75. 75. Thread Thread thread = new Thread(null,doInBackground,”background”); Runnable doInBackground = new Runnable(){ public void run(){ myBackgroundProcess(); } Q- How can I update the Main thread ? 75
  76. 76. Thread MQ • Click on a button component is “translate” into a message which is being dropped on to the main queue. • Main thread listen to the main Q and process each incoming message. • Handler are used to drop messages on the main queue usually from a separate thread. • Message also holds a data structure that can be passed back to the handler Understand looper: 76
  77. 77. Handler/Looper (message loop for a thread) • Looper is a class that turns a thread into a Pipeline Thread (Q) • Handler gives you a mechanism to push tasks into it from any other threads. – – Each Handler instance is associated with a single thread (actually with that thread message queue) this is done during the handler creation and initialization. – 77 A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. When the main thread retrieves messages, it invokes the handler that dropped the message through a callback method “handleMesage” on the handler object.
  78. 78. Working with Threads • Create a handler in the main thread. • Create a separate thread that does the actual work. and pass it the handler • The separate thread can do the work for longer than 5 seconds, and to send messages to the main thread by the handler. • The messages get processed by the main thread • The main thread will invoke the handler callback methods (the message holds reference to the handler) 78
  79. 79. private Handler handler = new Handler(){ //in the main thread create Handler object Handler @Override public void handleMessage(Message msg){ // main thread will response to the handler callback m_ProgressDialog.setTitle(msg.getData().getString("messageLabel")); // run in main thread; } }; Private Thread thrd = new Thread(){ // in the main thread, create another thread and pass it the handler public void run(){ // BackgroundProcess - This code run in a separate Thread doSomeLengthyWork(); Message message = handler.obtainMessage(); Bundle bundle = new Bundle(); bundle.putString("messageLabel", "thread finished"); message.setData(bundle); handler.sendMessage(message); // send message to the main Q (handler.postAtTime()); //postDelay / postAtTime } thrd.start(); Private Runnable updateUIRunnable = new Runnable(){ public void run(){ updateUI(); // This Code run in the main thread } 79 }
  80. 80. HandlerThread Start a new thread that has a looper, The looper can then be used to create handler classes Public class MyClass implements android.os.Handler.Callback Public void dummy(){ // Create and start the HandlerThread - it requires a custom name HandlerThread handlerThread = new HandlerThread("MyHandlerThread"); handlerThread.start(); Looper looper = handlerThread.getLooper(); // Get the looper from the handlerThread Handler handler = new Handler(looper, this);  will send the to the HandlerThread Q instead of Main Q handler.sendMessage()  will send the to the HandlerThread Q instead of Main Q handlerThread.quit(); // Tell the handler thread to quit } @Override public boolean handleMessage(Message msg) { …. // run in HandlerThread 80 }
  81. 81. Working with Thread API • handler - main thread getting updated by “handleMessage” callback method. • runOnUiThread - update the main thread, from a sub thread. • AsyncTask (android 2.2) manage the creation of the background thread and update the main thread using “onPostExecute” callback method. – AsyncTask are not persist across activity restart meaning that in case device has been rotate the activity will be destroyed and restart and the asyncTask will be canceled, therefore its recommended to start service and in that service to run asyncTask. • AsyncTaskLoader (android 3.0) – improve AsyncTask (data was lost across Activity configuration changes, each time the activity returns from a stopped state an refresh data call has been invoked). • background.html
  82. 82. runOnUiThread • Thread thread = new Thread(new Runnable() { public void run() { // ... // do long running tasks here // … // running in Activity context runOnUiThread(new Runnable() { public void run() { // ... // update UI here // ... } }); } }); thread.start(); 82
  83. 83. AsyncTask public void useTask() { new FooTask().execute("param1", "param2"); } <input param, progress param, result param> class FooTask extends AsyncTask<String, Integer, Long> { protected Long doInBackground(String... params) { publishProgress(progress); // do long running tasks here in a separate thread return result; } protected void onProgressUpdate(Integer... progress) { // update progress to UI } protected void onPostExecute(Long result) { myTextView.setText(resault); // update UI here } } 83
  84. 84. Run AsyncTask • Asynctask can be execute only once ( if you will try to run again you will get exception) meaning: new DownloadFilesTask().execute(url1, url2, url3); new DownloadFilesTask().execute(url4, url5, url6); you can NOT do the following: DownloadFilesTask dfTask = new DownloadFilesTask(); dfTask().execute(url1, url2, url3); dfTask().execute(url4, url5, url6); 84
  85. 85. Loader (AsyncTaskLoader) • Loaders are responsible for – performing async tasks on a separate thread, – monitoring the data source for changes, and delivering new results to a registered listener (usually the LoaderManager) when changes are detected. • Loader available within any activity/fragment via LoaderManager • AsyncTaskLoader, CursorLoader (will be explained later). • 85
  86. 86. Use Loader Activity/Fragment can implements LoaderCallbacks<T> From Activity.onCreate() or Fragment.onActivityCreated() call to getLoaderManager().initLoader(LOADER_ID like „0‟, args, this or callback); After loader has been created, calling initLoader again will return the existing object, use restartLoder in order to recreate loader object (use it in case the query parameters has been change) public Loader<T> onCreateLoader – use to create loader public void onLoadFinished(Loader<T> loader, T data) – update UI like textView.setText(data); public void onLoaderReset(Loader<T> loader) – will always be invoked when you leave the activity, release reference to the data that was returned , also reset UI like setText(null) 86
  87. 87. Create Custom Loader- Observer Loaders should implement an observer in order to monitor the underlying data changes. When a change is detected, the observer should call Loader.onContentChanged(), which will either: • force a new load if the Loader is in a started state • raise a flag indicating that a change has been made so that if the Loader is ever started again, it will know that it should reload its data. 87
  88. 88. Class myLoader extends AsyncTaskLoader<T> onStartLoading(): First method which is being invoked, should invoke forceLoad() In this method you should register Observesr loadInBackground() run in a background thread deliverResult() Called when there is new data to deliver to the client. The Observers will invoke myLoader.onContentChanged() correspond to data changes 88
  89. 89. Loader states: Any given Loader will either be in a started, stopped, or reset state • Loaders in a started state execute loads and may deliver their results to the listener at any time. Started Loaders should monitor for changes and perform new loads when changes are detected. Once started, the Loader will remain in a started state until it is either stopped or reset. This is the only state in which onLoadFinished will ever be called. • Loaders in a stopped state continue to monitor for changes but should not deliver results to the client. From a stopped state, the Loader may either be started or reset. • Loaders in a reset state should not execute new loads, should not deliver new results, and should not monitor for changes. When a loader enters a reset state, it should invalidate and free any data associated with it for garbage collection (likewise, the client should make sure they remove any references to this data, since it will no longer be available). 89
  90. 90. Service
  91. 91. Service: • Services are background process, which has no user interface, they are used for long running operation and also to expose functionality for external applications. • you can update UI from service via notification/toast • A Service is not a thread (Services by default are running on the main thread , just open a service for long time action is not enough, you must open a thread inside) • Services run with a higher priority than inactive or invisible activities and therefore it is less likely that the Android system terminates them. • Service which is bound to a focus activity or labeled as run in the foreground will almost never be killed – recommended not to use this option • If the system kills your service, it restarts it as soon as resources become available again, 91 you must design it to gracefully handle restarts by the system, depand on the service type !!!
  92. 92. Lifecycle • There are 2 kinds of services: – Started (local)- send & forget • starts it by calling startService(), • The service will run until the service or someone else explicitly stop it stopService() or stopSelf() has been called, or in case OS need to release resources, in that case OS will restart the service. – Bound (Remote) – • starts it by calling bindService(), does not call onStartCommand() • return a reference onBind() to the service, which allows to invoke the service methods from another class • Can expose methods (aidl) to other applications. • bound service runs only as long as another application component is bound to it, When all clients disconnect, or unbind, Android will stop 92 that Service.
  93. 93. Start Service • Start by calling – startService(new Intent (this,MyService.class); – startService (new Intent (MyService.PLAY_MUSIC)); • Finish by calling – – • stopService() from the activity stopSelf() from the service class onCreate() will be invoked only once ! (first lunch or after OS restart it) • OnBind might return instance or null • onStartCommand() - this is where you will open a worker thread, called whenever a client calls startService() • Calling startService() after the service has been started (meaning while it‟s running) will not create another instance of the service, but it will invoke the service‟s onStart()/onStartCommand() method again not the onCreate(), 93
  94. 94. Start service Flags– Restart The Service onStartCommand() return a flags: – – 94 Service.START_STICKY – (DEFAULT) • If the service killed by OS, it will restart when sufficient resource will be available again, OS recreate the service and call onStartCommand() with a null intent, unless there were pending intents to start the service, in which case, those intents are delivered. Service.START_NOT_STICKY • OS will not automatically restart the service, the service will restart only if there are pending StartService calls. • use it in case your service can be stopped and start later in next scheduled interval
  95. 95. Start service Flags– OS Restart The Service onStartCommand() return a flags: – Service.START_REDELIVER_INTENT • if OS terminate the service it will be restart only if there are pending start calls or in case the process end before the service called to stopSelf(). • Use it when its important to know that the service task has been finished property. After OS restart the service the passed intent will be: • null in case of START_STICKY (unless there are pending startService calls) • original intent in case of START_REDELIVER_INTENT 95
  96. 96. Start service - IntentService A subclass of Service which open a worker thread to handle all start requests , one at a time (Q not async not parallel like Service) – The onHandleIntent() - use this method to execute the background task , no need to create a new thread. – After all received intent has been processed (onHandleIntent() returns) the service is destroyed. (no need to implement onStartCommand or onDestroy) 96 This is the best option if you don't require that your service handle multiple requests simultaneously. You cant use stopService() or stopSelf() The IntentService is built to stop itself when the last Intent is handled by onHandleIntent(Intent).
  97. 97. Start Service after Device Reboot (not bind service !) <manifest xmlns:android= package="com.Test"> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/> <application> <receiver android:name=".BootCompletedIntentReceiver"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> </intent-filter> </receiver> <service android:name=".BackgroundService"/> </application> </manifest> public class BootCompletedIntentReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) { Intent pushIntent = new Intent(context, BackgroundService.class); context.startService(pushIntent); } 97 }
  98. 98. Getting response from start service Updated from services will be usually using broadcast mechanism (next section) – BroadcastReceiver – send/get data/notifications across applications, whenever you send broadcast its sent system wide – LocalBroadcastRecevier / ResultReceiver – send/get data internal to application, Your application is the only receiver of the data • • 98
  99. 99. Bind Service (RemoteService= Service in a different process) • support a Remote Procedure Call (RPC) mechanism to allow external app‟s, on the same device, to connect to the service • onBind() must return instance to the service object • Bind service ~ the service is like a member in your app AIDL allows to transfer objects across process‟s (~intent) • Android Interface Definition Language is used in order to define the service to other applications • AIDL allows you to pass java primitive (char,int) , String, List, complex types (percable) • Create AIDL file in src folder, android will generate class from the aidl file (~stub) 99
  100. 100. Bind Service RemoteCallbackList: "If a registered callback's process goes away, this class will take care of automatically removing it from the list. If you want to do additional work in this situation, you can create a subclass that 100 implements the onCallbackDied(E) method."
  101. 101. Reconnect bind service after service crush • onServiceDisconnected – Called when a connection to the Service has been lost. This typically happens when the process hosting the service has crashed or been killed. This does not remove the ServiceConnection itself , binding to the service will remain active. Local Service: run in the same process of the application (if app is closed the service will be closed as well) cant reconnect ! Remote Service: Service is running in separate process, when this process has crashed or been killed, only the actual service is destroyed, the activity lives in another process that bound to the service is remained, therefore you can reconnect to existing service 101
  102. 102. Remote Service Consumer – client (RemoteServiceClient) • Copy the AIDL file to the client application (in same package like in the service application • Use bindService() and not startService() in order to invoke the service • you cant assume that after calling to bindService() the service will be available !!! bindService() is asynchronous. • When the connection to the service is established, the onServiceConnected() callback is invoked • onServiceDisconnected() callback does not get invoked when we unbind from the service, It is only invoked if the service crashes. • 102
  103. 103. Bind Service new flags • BIND_ADJUST_WITH_ACTIVITY- set the service priority according to the bound activity • BIND_ABOVE_CLIENT / BIND_IMPORTANT – set the priority to as forground • BIND_NOT_FORGROUND 103
  104. 104. Service – Process <service android:name="MyService" android:icon="@drawable/icon“ android:label="@string/service_name" android:process=":my_process" > </service> • Usually you will not add android:process, unless the service is remote (android:process=":remote“) • Running a service in its own process gives it its own memory address space and a garbage collector of the virtual machine. • Even if the service runs in its own process you need to use asynchronous processing (Thread) to perform network access. 104
  105. 105. Mixed Service (Start & bind service) • Implements both: onStartCommand() to allow components to start it and onBind() to allow binding. • Mixed mean that OS will keep the service running as long as its not explicitly stopped or there are no client bound to it. • The hybrid approach is very powerful and common way to use Services: let‟s say we are writing an app that tracks user location. We might want the app to log locations continuously for later use, as well as display location information to the screen while the app is in use. If you will only bind the service during application launch, you will get the location update, but when the application will close the service will be destroyed as well  , therefore you should also use start service approach in order to verify that the server will remain running until it will explicitly close.  105
  106. 106. Block UI thread ? The Service will block the calling Activity until the service is started • The best way in this case is to start a new thread and then call a service from there. • Intentservice is a another solution 106
  107. 107. Summary: • Start service - can be restart by OS , can be started after reboot, pay attention to onCreate(), onStartCommand() 107
  108. 108. Summary 108
  109. 109. Service – External Permission • “android:exported = false” determine whether or not other applications can invoke the service or interact with it. • like an activity, a service can define intent filters which allow other components to invoke the service using implicit intents, If you plan on using your service locally (other applications will not be able to use it), then you should not add intent Filters • android:exported Default value is false if there are no intent filter, and true if there are. • There are more flags like : FLAG_GRANT_READ_URI_PERMISSION 109
  110. 110. Set service as Foreground • Start service can set its priority as foreground by calling startForeground(notification_id,notification) – foreground services are expected to have interaction with the user (like player service) – This is not recommended as the OS will not kill the service and will make it hard to recover from resource starvation situations. • bindService(intent,connection,Flag) can use its flag to set its priority like BIND_IMPORTANT which is similar to Forground • If there are clients bound to the service, and one of its clients is visible to the user, then the service itself is considered to be visible. 110
  111. 111. Toast from a Thread in a service Toast can be shown only from UI Thread (Main Thread) 111
  112. 112. links • • • • 112
  113. 113. Wake Lock
  114. 114. WakeLock & Service • In case device is sleeping (screen not in use) and service needs to restart ,it require the device to be a wake //acquire a WakeLock: PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); PowerManager.WakeLock wakeLock = pm.newWakeLock(pm.SCREEN_DIM_WAKE_LOCK, "My wakelook"); // This will release the wakelook after 1000 ms wakeLock.acquire(1000); // Alternative you can request and / or release the wakelook via: // wakeLock.acquire(); wakeLock.release(); 114
  115. 115. Another way Wake from activity • getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); • myActivity.getWindow().addFlags( WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD); • (WakefulIntentService ) 115
  116. 116. Broadcast
  117. 117. Receiver: Android support event-driven application: • Sender Application call to sendBroadcast(intent) which is asynchronous • applications can register to those intents or system events (SMS,Low memory) by extending BroadcastReceiver • We should avoid long running tasks in Broadcast receivers. For any longer tasks we can start a service from within the receiver. • Broadcast are used to restart service after device reboot, update activity from a service • Security - Make the broadcast receiver unavailable to the external applications using android:export=”false”. Otherwise other applications can abuse them. Types: – 117 BroadcastReceiver – send data/notifications across system wide applications, – LocalBroadcastRecevier / ResultReceiver – send data internal to application.
  118. 118. Send broadcast 118
  119. 119. Register receiver – static (manifest) Intent intent = new Intent(GET_MESSAGE); // late Banding sendBroadcast(intent); Class ReceiverClient extends BrodcastReceiver { @override Public void onReceive(Context context, Intent intent){ // run on main thread . . . (context can be use to start activity/service…) } • Manifest : <receiver android:name=".ReceiverClient"> <intent-filter> <action android:name="com.dori.getMessage" /> </intent-filter> 119 </receiver>
  120. 120. Register receiver dynamic (programmatically) onResume(){ registerReceiver(receiver,intentFilter); } onPause(){ unRegisterRecevier(recevier); } 120
  121. 121. LocalBroadcastManager • Used to register and send broadcasts of Intents within your process. This is faster and more secure as your events don't leave your application. LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(“WOW”)); - Send In Activity: private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { ... } @Override public void onResume() { //register LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, new IntentFilter(“WOW")); } @Override protected void onPause() { // Unregister since the activity is not visible LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver); } 121
  122. 122. 122
  123. 123. Working with Broadcast – By registering a Broadcast Receiver, application can listen for broadcast Intents that match specific filter criteria. – broadcast message can be received by more than one receiver (Receiver) – Broadcast receiver has 10 sec‟ to do action till application will throw ANR message (application not responding) unlike activity which has 5 seconds – By default run on the main thread – Broadcast Receivers will automatically start application to respond to an incoming Intent. • As of Android 3.1 the Android system will by default exclude all BroadcastReceiver from receiving intents if the corresponding application has never been started by the user. – Unlike a service, a broadcast receiver cant be restarted 123
  124. 124. Long run receiver Example: If you want a receiver that will listen to incoming SMS and will handle SMS which comes from specific location: 1. Acquire a wakelock in the receiver (listen also to BOOT_COMPLETED) 2. start service from the receiver (in case process will be shut down to clean resources, service will restart) 3. Start a separate thread from the service (avoid the 5sec limit of main thread) 4. The background thread will post a message through a handler back to the service 5. The background thread will update the service to stop itself either directly or through a handler 6. Have the service release the wake lock 124
  125. 125. Broadcast advanced • Normal broadcasts (sent with Context.sendBroadcast) are completely asynchronous. All receivers of the broadcast are run in an undefined order, often at the same time. • Ordered broadcasts (sent with Context.sendOrderedBroadcast) are delivered to one receiver at a time. As each receiver executes in turn (Q), it can propagate a result to the next receiver, or it can completely abort the broadcast so that it won't be passed to other receivers. The order receivers run in can be controlled with the android:priority attribute of the matching intent-filter. • sendStickyBroadcast (intent) – – A normal broadcast Intent is not available anymore after is was send and processed by the system. Perform a sendBroadcast(Intent) that is "sticky," meaning 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), by register to sticky event you don‟t need to wait for next event to be trigger in order to get the data (Battery level) 125
  126. 126. Links • • • 126
  127. 127. Pending Intent & Alarm Manager
  128. 128. Pending Intent • Android allows a component to store an intent for future use by wrapping intent with PendingIntent . • A PendingIntent is an intent that you give to another application (Notification Manager, Alarm Manager, or other 3rd party applications), which allows the foreign application to use your application's permissions to execute a predefined piece of code, on your behalf, at a later time. • If you give the foreign application an Intent, they will execute the Intent with their own permissions. But if you give a PendingIntent , that application will execute the contained Intent using your permission. • To get PendingIntent you will not use C‟tor (Android manage pool of PendingIntent) – PendingIntent.getActivity(context, requestCode, intent, flags)//start activity – PendingIntent.getService(context, requestCode, intent, flags) //start service – PendingIntent.getBroadcast(context, requestCode, intent, flags) // call broadcast receiver flag indicates what to do if there is an existing pending intent – whether to cancel it, overwrite its extra data.. request code/id is used to distinguish two pending intents when their underlying intents are the same. For example AlarmManager will invoke the last call in case you will use pending intent with same 128 Id, but if you will use different Id then AM will invoke all calls
  129. 129. Why id is important 129
  130. 130. Alarm Manager (Scheduler) • Used to trigger event at specific time or schedule EVEN IF THE APPLICATION IS CLOSED. They are managed outside of the application scope. • If the application is running it probably be better to invoke timer tasks with Timer/Threads/Background services. • Usage: • get Alarm Manager instance • Provide to the Alarm Manager, PendingIntent which will be caught by the receiver One time: alarmManager.set(AlarmManager.RTC_WAKEUP, firstTime, pendintIntent); Repeat : am.setRepeating(AlarmManager.RTC_WAKEUP, firstTime, 5*1000, pendintIntent);//every 5 sec 130
  131. 131. Alarm Manager Flags: – – RTC • fire the intent but not wake the device – ELAPSED_REALTIME • fire the intent based on the amount of time since device was reboot but does not wake the device – 131 RTC_WAKEUP • wake the device from sleep in order to fire the intent ELAPSED_REALTIME_WAKEUP • wake the device and fire intent after amount of time has passed since device has been reboot
  132. 132. Persistence
  133. 133. Persistence • Android provide 3 kinds of persistence: – Shared Preferences (Properties files) – Files – Database 133
  134. 134. Shared Preferences (properties files) – Fast & Easy Persistent mechanism – Support for primitive ,Boolean, string, float, long, and integer – Can be private to the application or global(shared) to all applications • Preferences files located at (emulator) : data/data/<package name>/shared_pref/<preferences name> SharedPreferences preferences = getSharedPreferences("myPref", MODE_PRIVATE); preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); Editor editor = preferences.edit(); editor.putString("mykey", “mayValue”); editor.commit(); //in activity A preferences.getInt("mykey", “defaultValue”) // in activity B 134
  135. 135. Shared Preferences – UI (select option from list) • Android provide built-in UI preferences classes like : CheckBoxPreference , EditTextPreference, PreferencesActivity, those object has onSharedPreferencesChangeListener for ui changes. 135
  136. 136. The „Activity‟ Special Shared Preferences • Activity.getPreferences(Mode.Private) without specify name – this is used to save activity preferences which are not shared with other objects in the application. • Bundle in onCreate(bundle)/ onSaveInstanceState(bundle) , onRestoreInstantState(bundle) is a private case of shared preferences that will not be share among other activities in the same application, this is used to persist UI state in case OS terminate the activity and restart it like Rotate device. 136
  137. 137. Files // private file associated with this Context's application package FileOutputStream fos = openFileOutput(FILE_NAME, Context.MODE_PRIVATE); FileInputStream fis = openFileInput(FILE_NAME); • File Management Tools : – DeleteFile – FileList – array with all files name which has been created by the application 137
  138. 138. Database (SqlLite) • SqlLite is an relational database that comes with android – stored at /data/data/<package_name>/databases (visible from emulator) – By default, all databases are private, accessible only by the application that created them. – To share a database across applications, use Content Providers – Android save database version and compare it during app upgrade in order to verify it DB needs to rebuild. – 138 GUI tool ,
  139. 139. Create & work with DB: 139
  140. 140. SqlLite: • sqlLiteOpenHelper object used to manage the logic of create/update DB/Table This object also provide cache mechanism and – getWritableDatabase() - create and/or open a database that will be used for reading and writing. – getReadableDatabase() - create and/or open a database • Queries in Android are returned as Cursor objects. Cursor cursor = query( table ,// from columns, //Which columns to return like new String[]{FIRST_COLUMN,SECOND_COLUMN}; selection, // select criteria selectionArgs, //criteria values groupby, having, 140 order);
  141. 141. Working with cursor • You need to use moveToFirst() because the cursor is positioned before the first row. • The cursor can move forward and backward. if (cur.moveToFirst() == false) //no rows empty cursor return; while(cur.moveToNext()) //cursor moved successfully //access fields 141
  142. 142. Working with cursor All field-access methods are based on column number, so you must convert the column name to a column number first : • You need to know the column names : int column_Index=cur.getColumnIndex(“age”); //2 • You need to know the column types : int age = cursor.getInt(column_Index) • ContentValues objects are used to insert new rows into tables ContentValues contentValues = new ContentValues(); contentValues.put("name", person.getName()); contentValues.put("age", person.getAge()); db.insert(DATABASE_TABLE, null, contentValues); 142 //30
  143. 143. Cursor usage • it‟s strongly recommended that all tables include an auto increment key field called “_id” which is mandatory for contentProvides which represents the row ID. 143
  144. 144. SQL FTS • If your data is stored in a SQLite database on the device, performing a full-text search (using FTS3, rather than a LIKE query) can provide a more robust search across text data and can produce results significantly faster. • FTS = creating virtual tables which in fact maintain an inverted index for full-text searches 144
  145. 145. ORM • 145
  146. 146. ViewBinder • Use it In case you need to change the display format of the values fetched by cursor (different display for dateTime) • Cursor.setViewBinder() 146
  147. 147. NoSql 147
  148. 148. Content Provider
  149. 149. Content Provider • Content Provider are used to share data among applications without exposing the storage layer (for example retrieve contact list) • Access to Content Providers is handled by the ContentResolver (query, insert, update, delete) • Syntax is REST-like URIs, – Retrieve a specific book (23) • content:// – Retrieve all books • content:// 149
  150. 150. ContentProvider require to Manage the Cursor • startManagingCursor(cursor) – – Manage the Cursor lifecycle within your Activities. • When the activity terminates, all managed cursors will be closed. • when the activity is paused, it will automatically deactivate the cursor. • Invoke requery() on the cursor each time the activity returns from a stopped state • managedQuery – A wrapper around the ContentResolver's query() + startManagingCursor(cursor) – performs a query on the main UI thread  using ContentResolver's query() require to manage the Cursor (startManagingCursor) 150
  151. 151. ContentProvider - queries • Example: Uri contacts_uri = Contacts.People.CONTENT_URI; (android built in provider) string[] projection = new string[] {People._ID,People.NAME,People.NUMBER ; Cursor managedCursor = getContentResolver (). managedQuery( contacts_uri, //URI projection, //Which columns to return. “id=“, // WHERE clause new String[] {23} , // where values Contacts.People.NAME + " ASC"); // Order-by clause. 151
  152. 152. ContentProvider – queries (/23) • Example: Uri contacts_uri = Contacts.People.CONTENT_URI; (android built in provider) Uri myPersonUri = peopleBaseUri.withAppendedId(contacts_uri , 23); string[] projection = new string[] {People._ID,People.NAME,People.NUMBER ; Cursor managedCursor = getContentResolver (). managedQuery ( myPersonUri , //URI in this example its already include where people.Id=23 projection, //Which columns to return. null, // WHERE clause null, // where values Contacts.People.NAME + " ASC"); // Order-by clause. • Demo (Ex8 –must create 2 contacts person before) 152
  153. 153. ContentProvider – add new data • Adding new entry ContentValues values = new ContentValues(); values.put("title", "New note"); values.put("note","This is a new note"); ContentResolver contentResolver = activity.getContentResolver(); Uri uri = contentResolver.insert(Notepad.Notes.CONTENT_URI, values); This call returns a URI pointing to the newly inserted record 153
  154. 154. Create custom Content Provider – – Implement methods: query, insert, update, delete, and getType. – Register the provider in the manifest file. – 154 Extend the abstract class ContentProvider. Example
  155. 155. CursorLoader (3.0+) It‟s a loader that queries the ContentResolver and returns a Cursor From Activity/fragment: LoaderManager lm = getLoaderManager(); lm.initLoader(LOADER_ID, null, loaderCallback); //create or reuse loader LoaderCallbacks<Cursor> loaderCallback = new LoaderCallbacks<Cursor>() { @Override public Loader<Cursor> onCreateLoader(int id , Bundle arg1) { if(id==LOADER_ID){ return new CursorLoader(context, CONTENT_URI, null, null, null, ContactsContract.Contacts.DISPLAY_NAME + " ASC"); } } @Override public void onLoadFinished(Loader<Cursor> loader, final Cursor cursor) { if(loader.getId()== LOADER_ID){ updateView(cursor); // in main thread } @Override public void onLoaderReset(Loader<Cursor> loader) { // Loader's data is now unavailable Remove any references to the old data by replacing it a null Cursor. 155 } updateView(null)
  156. 156. Why Use Loader ? • CursorLoader handle cursor lifetime , instead of to use manageQuery , startManagingCursor – Requery() will invoke only when underline data has been changed , (activity restart will not trigger it) – all cursor operations are done asynchronously, main thread is safe. • No need to implement Observer , has cursorLoader observer any data changes • • 156
  157. 157. Loader with without ContentProvider ? • • Since Android‟s CursorLoader is only for Cursors returned by content providers we need another Loader implementation if we want to use SQLite directly. 157
  158. 158. Location-API (location data) Location API V2 Mapping-API (display location)
  159. 159. Location providers: • GPS: – is most accurate, – it only works outdoors, – it quickly consumes battery power, – doesn't return the location as quickly as users want. • Network Location Provider determines user location using cell tower and Wi-Fi signals – providing location information in a way that works indoors and outdoors, – responds faster, – uses less battery power. 159
  160. 160. Best performance Fuse Location (12:18) 160
  161. 161. Location API • Depending on the device, there may be several technologies (Location Provider) to determine the location. • You cant assume that GPS for example will be available on all devices or that its already enable when you will use it. • Location Provider, can offer different capabilities like power consumption, accuracy, the ability to determine altitude, speed, distanceBetween() 161
  162. 162. New One API new location api LocationClient (context, GooglePlayServicesClient client, …) onStart()/onStop() you will need to invoke mLocationClient.connect()/disconnect(). ActivityRecognitionClient - detect if the user is currently on foot, in a car, on a bicycle or still. 162
  163. 163. Getting Location details (old API) Location location = locationManager.getLastKnownLocation(provider) • Return the last known location, Location object hold all information from provider like speed... • If the device has not recently updated the current location may be out of date!!! • To get updates when location has been changed use locationManager.requestLocationUpdates(provider, 9000,200,locationListener); best practice to minimize update call by time/distance like in the example : 9 seconds, 200 meters • To stop location updates: locationManager.removeUpdates(myLocationListener); 163
  164. 164. Get Provider (old API) • LocationProvider.getProvider(providerName) is used to specify which provider you want like GPS • Another option is specify the requirements (criteria) that a provider must meet and let Android return the best provider to use. Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_COARSE); criteria.setPowerRequirement(Criteria.POWER_LOW); criteria.setAltitudeRequired(false); criteria.setBearingRequired(false); criteria.setSpeedRequired(false); criteria.setCostAllowed(true); String bestProvider = locationManager.getBestProvider(criteria, true); 164
  165. 165. Proximity (old API) – GeoFencing (new API) • • 165 application can listen to proximity alert which will fire if the device crosses over that boundary, both when it moves within the radius and when it moves beyond it To set proximity you need to provide the following parameters: – select the center point :longitude and latitude – radius around that point, – expiry time-out for the alert.
  166. 166. Projection (Screen to GeoPoint) Translate between latitude/longitude coordinates (stored as GeoPoints) and x/y screen pixel coordinates (stored as Points). When user click on the screen you will probably want to know the geo location coordinates of the user click • GoogleMap.OnMapClickListener (onMapClick(LatLng point)) • Projection proj = mMap.getProjection(); Point startPoint = proj.toScreenLocation(new LatLng(-31.952854, 115.857342)); LatLng myLat= proj.fromScreenLocation(startPoint) // Android 2.0 code Projection projection = mapView.getProjection(); projection.toPixels(geoPoint, myPoint); //to screen cords projection.fromPixels(myPoint.x, myPoint.y); //to GeoPoint 166
  167. 167. Geocoder (Address to GeoPoint) • • • • • Translate between street addresses and longitude/latitude map coordinates (contextualized using a locale) Return a list of Address objects. Which contain several possible results, up to a limit you specify when making the call Geocoder lookups should be perform in separate thread The accuracy and granularity of reverse lookups are entirely dependent on the quality of data in the geocoding database; as such, the quality of the results may vary widely between different countries and locales. if no matches are found, null will be returned. Geocoder geocoder = new Geocoder(getApplicationContext(),Locale.getDefault()); List<Address> addresses = geocoder.getFromLocation(latitude, longitude, number_of_results); String streetAddress = “160 Riverside Drive, New York, New York”; 167 List<Address> result =geocoder.getFromLocationName(aStreetAddress, number_of_results);
  168. 168. Permission • Adding permission to the manifest: <uses-permission android:name=”android.permission.ACCESS_FINE_LOCATION”/> - GPS <uses-permission android:name=”android.permission.ACCESS_COARSE_LOCATION”/> - Network • You cant assume that the GPS/WIFI are enable you need to check in code locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) With new API you need to check that GoogleServices are used) • In order to open location settings screen startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS), 0); 168
  169. 169. Map API (paint the map, add icons) Google Map handles the following operations: – Connecting to the Google Maps service. – Downloading and display map tiles. – Manage controls such zoom. – Allows to add icons on the map. What is new in V2 (3D & indoor support) 169
  170. 170. Usage: 170 Tutorial
  171. 171. MapFragment (recommended) • MapFragment is a subclass of the Android Fragment class, allows you to place a map in an Android Fragment. • MapFragment objects act as containers for the map, and provide access to the GoogleMap object. • SupportMapFragment class (API -12 backward compatibility) 171
  172. 172. MapView • MapView is a subclass of the Android View class, allows you to place a map in an Android View. • MapView acts as a container for the Map, exposing core map functionality through the GoogleMap object. • Users of this class must forward all the life cycle methods from the Activity or Fragment containing this view to the corresponding ones in this class (onCreate()…) 172
  173. 173. Overlay A Ground overlay - an image that is fixed to a map A Tile Overlay is a set of images which are displayed on top of the base map tiles. These tiles may be transparent, allowing you to add features to existing maps unlike other overlays, if the map is recreated, tile overlays are not automatically restored and must be re-added manually. 173
  174. 174. Mapping API (api version1 ) MapView – Map Layout supports several modes: map, street view, satellite, and traffic MapActivity - Special activity which handle map activities MapController is used to control the map, allowing you to set the center location and zoom levels. Overlay – used to draw layers via canvas on top the map, The Overlay class itself cannot be instantiated, so you‟ll have to extend it or use one of the extensions. MyLocationOverlay is a special overlay that can be used to display the current position and orientation(Compass) of the device. ItemizedOverlays provide a convenient way to create Overlay with image/text handles the drawing, placement, click handling, focus control, and layout optimization of each OverlayItem marker for you. 174
  175. 175. Debug
  176. 176. Debug log messages: • Log.i(“tag”,”message”); Trace File: Create log files that give details about an application, such as a call stack and start/stop times for any running methods. • Debug.startMethodTracing(“myFile”) - create a trace file mnt/sdcard/myFile.trace (put in onCreate() and stopMethodTracing , in onStop(), don‟t put in onDestroy()) • 176 Use TraceView from DDMS (or run it as standalone utility) to view the result
  177. 177. TraceView Execution timeline Why is something running on the main thread for that long? profiler analysis 177 Function statistics A call about time zones is taking this long?
  178. 178. StrictMode Report violations of policies related to threads and virtual machine (memory leak, IO). most commonly used to catch accidental disk or network access on the application's main thread. If a policy violation is detected, a stack trace will appear which will show where the application was when the violation occurred. 03-14 08:56:19.665: D/StrictMode(6309): StrictMode policy violation; ~duration=8925 ms: android.os.StrictMode$StrictModeNetworkViolation: policy=23 violation=4 03-14 08:56:19.665: D/StrictMode(6309): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork( 03-14 08:56:19.665: D/StrictMode(6309): at 03-14 08:56:19.665: D/StrictMode(6309): at 03-14 08:56:19.665: D/StrictMode(6309): at 03-14 08:56:19.665: D/StrictMode(6309): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection( 03-14 08:56:19.665: D/StrictMode(6309): at 03-14 08:56:19.665: D/StrictMode(6309): at 03-14 08:56:19.665: D/StrictMode(6309): at org.apache.http.impl.client.DefaultRequestDirector.execute( 03-14 08:56:19.665: D/StrictMode(6309): at org.apache.http.impl.client.AbstractHttpClient.execute( 03-14 08:56:19.665: D/StrictMode(6309): at org.apache.http.impl.client.AbstractHttpClient.execute( 03-14 08:56:19.665: D/StrictMode(6309): at org.apache.http.impl.client.AbstractHttpClient.execute( 03-14 08:56:19.665: D/StrictMode(6309): at com.dori.MyAct.getHttpContent( 178 03-14 08:56:19.665: D/StrictMode(6309): at com.dori.MyAct.onCreate(
  179. 179. Use StrictMode 179
  180. 180. Adb debug commands • Debug.dumpHprofData -Dump "hprof" data • Debug.dumpService -Get a debugging dump of a system service by name • Adb shell dumpsys - gives a wealth of information about the applications on the phone, and the current state of the phone • adb bugreport -Prints dumpsys, dumpstate, and logcat. 180
  181. 181. Http Connection
  182. 182. Http Clients: • HttpURLConnection • Apache HTTP Client • • DefaultHttpClient - Default implementation of an HTTP client AndroidHttpClient - Implementation of the Apache DefaultHttpClient that is configured with reasonable default settings and registered schemes for Android. Both support HTTPS, streaming uploads and downloads, configurable timeouts, IPv6 and connection pooling. • Best practice is to create one instance of HttpClient for the application (in the application object) 182
  183. 183. Which client is best? Apache HTTP client has fewer bugs on Eclair and Froyo. It is the best choice for these releases. From Gingerbread HttpURLConnection is the best choice. “New applications should use HttpURLConnection it is where we will be spending our energy going forward.” 183
  184. 184. Manifest Http Permission To access the Internet: android.permission.INTERNET To check the network state: android.permission.ACCESS_NETWORK_STATE. 184
  185. 185. HttpURLConnection HttpURLConnection conn = (HttpURLConnection) newURL(“”).openConnection(); InputStream is= conn.getInputStream(); 185
  186. 186. Apache Http Client HttpClient client = new DefaultHttpClient(); --------------------------------------------------------------------------------HttpGet request = new HttpGet(); request.setURI(new URI("http://myWebSite?param=value")); HttpResponse response = client.execute(request); --------------------------------------------------------------------------HttpPost request = new HttpPost(http://myWebSite); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(“param", "value")); UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params ); request.setEntity(formEntity); HttpResponse response = client.execute(request); 186
  187. 187. Rest: • Google-IO – REST App Development GuideLines • RestTemplate , examples RestTemplate restTemplate = new RestTemplate(); Map<String, String> vars = new HashMap<String, String>(); vars.put("hotel", "42"); vars.put("booking", "21"); String result = restTemplate.getForObject("{hotel}/bookings/{booking}", String.class, vars); String url = "{query}"; String result = restTemplate.getForObject(url, String.class, "whatever"); 187 restTemplate.getMessageConverters().add(new GsonHttpMessageConverter()); answer[] answers = restTemplate.postForObject(url, requestObject, answer[].class);
  188. 188. Rest Frameworks: • • • Crest RestEasy : resteasy-mobile RestEasy Restlet Web-Service Clients (Ksoap) 188
  189. 189. Web Server i-jetty – Install web server on android device 189
  190. 190. WebSocket 190
  191. 191. Volley Easy, Fast Networking for Android Code Example • • • • • • Invoke Http calls via Thread Pool not synchronic, Cache requests (rotate device) Faster (select http library like Spring – Android), Remove plumbing code, Cancel API Much more… 1- Create a request 2- Add to requestQ 3- The response is in the Main Thread 191
  192. 192. Security/Permission
  193. 193. Application Signature Android applications have to be signed with a digital certificate. upgrade application can be allowed only if it contain same signature, If you sign the application with a different signature, Android treats them as two different applications. Android tests the certificate‟s expiration only at install time. Once application is installed, it will continue to run even if the certificate expires But update will not be allowed in case application certificate expires. 193
  194. 194. Application signing involves 3 steps: • generate a certificate using the keytool • using the jarsigner tool to sign the .apk file with the signature of the generated certificate • Use zipAlign to minimize memory resources 194
  195. 195. 195
  196. 196. Application signing steps: • Create a folder to hold the keystore, for example c:androidrelease keytool -genkey -v -keystore "c:androidreleaserelease.keystore" -alias testAlias storepass password -keypass password -keyalg RSA -validity 14000 • jarsigner tool input parameters are the apk file which needs to be signed and the certificate. jarsigner -keystore c:androidreleaserelease.keystore -storepass password keypass password C:android_export_appgeocoder.apk testAlias (In order to create x.apk file: right-clicking an Android project in Eclipse  selecting Android Tools  selecting Export Unsigned Application Package) 196
  197. 197. ZipAlign • If the application contains uncompressed data like images Android can map this data in the memory, But the data must be aligned on a 4-byte memory • zipalign tool, moves uncompressed data not already on a 4-byte memory boundary to a 4-byte memory boundary • • 197 zipalign –v 4 infile.apk outfile.apk It is very important that you align after signing, otherwise, signing could cause things to go back out of alignment.
  198. 198. ProGuard • Java class file shrinker, optimizer, obfuscator, and preverifier. • It detects and removes unused classes, fields, methods, and attributes. • It optimizes bytecode and removes unused instructions. • It renames the remaining classes, fields, and methods using short meaningless names. • Usage can be taken for build.xml of Zxing application 198
  199. 199. uses-permission – During App Installation <uses-permission android:name="android.permission.INTERNET“/> <uses-permission android:name="android.permission.READ_PHONE_STATE“/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE“ /> <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE“/> <uses-permission android:name="android.permission.READ_CONTACTS" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 199
  200. 200. Permission - (permission + permissionClient apps) Using permission to protect resources <permission android:protectionLevel="normal“ android:name="com.myPermission“/> MyAct activity should be launched only by applications which have the “com.myPermission” permission <activity android:name=".MyAct“ android:label="@string/app_name" android:permission="com.myPermission"> </activity> Add to the client application (permissionClient , will open permission application) <uses-permission android:name="com.myPermission"></uses-permission> 200
  201. 201. URI permissions • Each application run within a separate process, which has a unique and permanent user ID (assigned at install time),this prevents one application from having direct access to another‟s data Partial permission: • In case you need to provide access finer than all or nothing,for example in case you need to show incoming emails but not their attachments • This is where URI permissions come in: • When invoking another activity and passing a URI, your application can specify that it is granting permissions to the URI being passed, By grantUriPermission() method and passing flag: Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION 201
  202. 202. Packaging - UserId • Each .apk file is uniquely identified by its root package name like “com.dori.test” which is specified in its manifest file, The package name is tied to the application signature • Android uses the package name as the name of the process under which to run the application, By default each package runs in its own process • User Id: Android allocates a unique user ID for each package process. The id is used as an ID for the underlying Linux OS • “shared user ID” allow applications to share data and even run in the same process Add in manifast: sharedUserId="com.test.mysharedusrid“ After adding it in the manifest you can use createPackageContext() which will return the context for the other application • Context targetContext = createPackageContext(“com.dori.test”, flag) targetContext.getResources(); 202
  203. 203. Lib Project
  204. 204. Library Projects (~jar with android context) • A library project is an android project which does not create a apk file • Maven genarete apkLib , while Gradle generate .AAR (android archive) 204
  205. 205. Sensors
  206. 206. Supported Sensors • • • • • • • • • • • 206 Temperature Accelerometer Gravity Gyroscope Rotation Magnetic Field Atmospheric Pressure Humidity Proximity – distance (cm) between device and target object Light Example Accelerometer
  207. 207. UI
  208. 208. Links UI generator tool IDE UI tips Android UI Tools Android Design Tips Android UI Patterns 208
  209. 209. Android special Views Surface View can be drawn from background thread but this option cost in memory usage. use with caution (when you need rapid updating the UI view (animation)). ViewStub is an invisible, zero-sized View that can be used to lazily inflate layout resources at runtime, when the viewStub is visible ViewStub then replaces itself in its parent with the inflated View or Views To Improve performance use ViewStub (lazy) 209
  210. 210. Theme <activity android:theme="@android:style/Theme.Translucent">  built in Theme (background to be transparent) Holo Light 210 Holo Dark Holo Light with dark action bars
  211. 211. Use style (~ css) <TextView style="@style/CodeFont" <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:textColor="#00FF00" android:typeface="monospace" android:text="@string/hello" /> 211 android:text="@string/hello" /> <?xml version="1.0" encoding="utf-8"?> <resources> <style name="CodeFont" parent="@android:style/TextAppearance.Medium"> <item name="android:layout_width">fill_parent</item> <item name="android:layout_height">wrap_content</item> <item name="android:textColor">#00FF00</item> <item name="android:typeface">monospace</item> </style> </resources>
  212. 212. Dashboard 212
  213. 213. ActionBar 213
  214. 214. ActionBar (new navigation) Navigating up Example 214
  215. 215. QuickAction 215
  216. 216. What is DP ? DP purpose is to remain the “same” UI element size from the user's point of view, regardless the screen resolution. android resolution 216
  217. 217. Scale UI Elements • When you define height/width UI element like Button its recommended not to use specific dimensions , use match_parent / wrap_content, • If you cant , Use sp or dp: • Dp (density independent pixels) – use this for non text elements • Sp (scale) – like dp but it is also scaled according to the user's font size preference. use this unit for font sizes, so they will be adjusted for both the screen density and user's preference. • Px (not recommended !!!) px = dp * (dpi / 160). scaleing is according to the space available and screen density. <support-screens android:smallScreens=“false” android:normalScreens=“true” android:requiersSmallestWidthDp=480 /> 217
  218. 218. Support multiple screens Android divides the range of actual screen sizes and densities into: • Categories sizes: small, normal, large, and xlarge • Categories densities: LDPI (low), MDPI (medium), HDPI (high), and XHDPI (extra high) To optimize application's UI its recommended to designing layouts/bitmap images per screen size. 218
  219. 219. 9Patch • To Scale PNG images use NinePatch-PNG : specify which parts of the images cab be stretched, and provide images per resolution draw9Patch 219
  220. 220. Gravity: • android:layout_gravity is the Outside gravity of the view (relative to the parent) • android:gravity is the Inside gravity of that View (its content alignment) Combination is supported: android:layout_gravity="center_horizontal|bottom" 220
  221. 221. android:layout_weight (like % in css) for table layout similar functionality is achieved via android:stretchColumns android:shrinkColumns android:collapseColumns 221
  222. 222. Usability Tips • Login should be simple (or limited) • Minimum navigate • Your mobile is personalize , your app should be too 222
  223. 223. Admin App 223
  224. 224. UI Adapter
  225. 225. Adapter • • • • Adapter are used to bind Data to Views. They are responsible for creating the child views Any data modification will cause the view to be updated You need to create just one row layout that will be repeat for all rows • • Support Functionality like scrolling, click on row. Basic adapters are : • • 225 ArrayAdapter SimpleCursorAdapter
  226. 226. Adapters ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,, android.R.layout.simple_spinner_item); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,new string[]{“A",“B",”C”}); “notifyDataSetChanged()” needs to be called after adding/deleting items to the adapter in order to update the view with the underline datasource changes. In case you are using cursorAdapter there is no need to invoke it. 226
  227. 227. Custom Adapters (ViewHolder pattern) In case you want to manage the display of child views: Create custom adapter by extending BaseAdapter ViewHolder Pattern improve performance by using cache as well as reusing the View Object, minimum calls to: • • LayoutInflater.from(context).inflate(R.layout.row, null); findViewById() ViewHolder Pattern adapters 227
  228. 228. How we can improve performance ? • Save the images that you already download in a SoftReference hashmap which allows to save data, if OS need to release memory it will delete the hashmap • Parallel loading images to screen • Use images thumbnails • Use volley Image loader • Use ViewHolder pattern 228
  229. 229. Toast
  230. 230. Toast • Show message on top application Toast.makeText(this,“myText”, Toast.LENGTH_LONG).show(); • 230 Create custom toast: Toast toast = new Toast(getApplicationContext()); toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0); toast.setDuration(Toast.LENGTH_LONG); toast.setView(layout); // some layout;
  231. 231. Notification
  232. 232. Notification • • • • Notifications let you notify users without interrupting their current Activities. it‟s a great way for getting a user‟s attention from within a Service or Broadcast Receiver. From notification you can invoke activities. Notification can have extra like sound, vibration, light RemoteViews (will be explained later) can be used to create custom notification view 232
  233. 233. Widget
  234. 234. Widget – • widgets are views which display on a home page and can be update frequently (timer), you can add more than one widget from the same type on the screen (usually with different settings). • Widget minimum time to update is 1H. • RemoteView - A class that describes a view hierarchy that can be displayed in another process. The hierarchy is inflated from a layout resource file, and this class provides some basic operations for modifying the content of the inflated hierarchy. • Widgets use RemoteViews to create there user interface. A RemoteView can be executed by another process with the same permissions as the original application. This way the Widget runs with the permissions of its defining application, meaning you can‟t work on the view directly. 234
  235. 235. Create Widget Code Example • Declare widget in manifest • Adding the AppWidgetProviderInfo Metadata (res/xml/) • Create widget layouts (View , configure) • Extends AppWidgetProvider This class is responsible to paint the RemoteViews according to the widget instance ID • Create Configuration Activity Instance parameters needs to be persistence 235
  236. 236. What's new • Since Android 4.2, it is possible to launch Home Screen application widgets on the Lock Screen of an Android device. • <appwidget-provider xmlns:android="" android:widgetCategory="keyguard|home_screen" ... > ... </appwidget-provider> 236