• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Dori waldman android _course
 

Dori waldman android _course

on

  • 1,653 views

Android course for developers from beginner to expert

Android course for developers from beginner to expert

Statistics

Views

Total Views
1,653
Views on SlideShare
1,653
Embed Views
0

Actions

Likes
2
Downloads
78
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

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
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • onRestoreInstanceState() is called only when re-creating activity after it was killed by the OS:orientation of the device changes (activity is destroyed and recreated)There is another activity in front of yours and at some point the OS kills your activity in order to free memory (for example). Why rotate (Ctrl-F11) cause application to restart ? Android supports runtime changes of language, location, and hardware by restarting application and reloading the resource values.This behavior can be override by overwrite onConfigurationChangedmethod usually application will be start fresh without saved state
  • onRestoreInstanceState() is called only when re-creating activity after it was killed by the OS:Orientation of the device changes (activity is destroyed and recreated)There is another activity in front of yours and at some point the OS kills your activity in order to free memory.This method is used to restore un commit UI state which has been save during onSaveInstanceStateusually application will start fresh without saved state
  • If more than one Location Provider matches your criteria, the one with the greatest accuracy is returned. If no provider is found, null is returned
  • alert will fire if the device crosses over that boundary, both when it moves within the radius and when it moves beyond it, with an extra keyed as LocationManager.KEY_PROXIMITY_ENTERING set to true or false accordingly
  • Android runs each application 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 dataPartial 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
  • In case our activity is running but not visible, and notification jump and we click on it and invoking our activity, we don’t want a new instance of our activity – use launchMode="singleTop“ in the manifest file to have one activity instanceIts recommended that service will not invoke an activity directly, instead it should create a notification, which will invoke the activity

Dori waldman android _course Dori waldman android _course Presentation Transcript

  • Android Development Dori Waldman
  • 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…)
  • Android Introduction
  • Course Resources http://developer.android.com/ http://developer.android.com/training/index.html http://www.xda-developers.com/category/android/ http://www.vogella.de/android.html 4
  • 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
  • Smart Phone definition ? • • 6 No standard (screen resolution / camera / GPS) More than 30 vendors (HTC, Samsung , Firefox …)
  • 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
  • The Pain of Native UI , or why Hybrid is poplar ? Same App on different devices/OS 2.3.4 Samsung 8 4.1 Samsung
  • Mobile Web Vs Desktop Web • 9 Web site should fit both – one development effort
  • Mobile Web Vs. Desktop Web • Same functionality ? No uploads View pictures taken nearby 10
  • 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
  • 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)
  • OS learning curve : Its not just New OS version , http://developer.android.com/google/play-services/index.html • 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
  • Android is not only for Phones/Tablet/Tv 14
  • Android Stack
  • Stack Linux Kernel provides hardware drivers, memory/power/network/security/thread management 16
  • 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
  • NDK • Allows to develop parts of the application using native-code languages such as C and C++ • http://developer.android.com/tools/sdk/ndk/index.html • Android C++ framework: – http://www.mosync.com/ – http://xamarin.com/monoforandroid 18
  • 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 • https://code.google.com/p/android-apktool/ • https://code.google.com/p/dex2jar/ • https://code.google.com/p/smali2java/
  • 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)
  • 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
  • First App
  • Recommended way to develop UI 23
  • Build UI (Code / XML) <LinearLayout xmlns:android=http://schemas.android.com/apk/res/android android:orientation="vertical" android:layout_width="fill_parent“ android:layout_height="fill_parent"> <TextView android: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
  • 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
  • Activity
  • 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
  • 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
  • Activity Lifecycle http://developer.android.com/reference/android/app/Activity.html 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
  • 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
  • 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
  • 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
  • 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
  • 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
  • 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
  • Activity Configuration *configChanges attribute prevent application from restart (rotate) http://developer.android.com/guide/t opics/manifest/activity-element.html 36
  • 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
  • Fragment
  • 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
  • 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
  • Static way to add fragment <linearLayout> <!– FragA is a class that extends Fragment - -> <fragment android:name=“com.dori.FragA”/> </linearLayout> 41
  • Dynamic way to add fragment (Frag container) <linearLayout> <FrameLayout android:id=“FragContainer” /> </linearLayout> FragmentTransaction ft = fragmentManager.beginTransaction(); Fragment frag = Ft.findFragmentById(R.id. FragContainer) ft.remove(frag); ft.add(R.id. FragContainer, MyFragB); ft.addToBackStack(“tag”); ft.commit(); 42
  • 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
  • Work with Fragments 44
  • Work with Fragments • working with fragments • http://www.vogella.com/articles/AndroidFragments/article.html • http://developer.android.com/guide/practices/tablets-and-handsets.html 45
  • 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
  • Intent
  • 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
  • Second way to invoke Intent: Intent intent = new Intent(); intent.setComponent( new ComponentName( "com.android.contacts“, "com.android.contacts.DialContactsEntryActivity“ ); startActivity(intent) 49
  • 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
  • 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
  • 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
  • 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
  • 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
  • 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
  • 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
  • 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
  • Send Sticky Intent Intent intent = new Intent("some.custom.action"); intent.putExtra("some_boolean", true); sendStickyBroadcast(intent); …. removeStickyBroadcast(Intent intent) 58
  • Manifest
  • <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/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
  • 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
  • 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
  • Resource
  • 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
  • • 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
  • 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
  • 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
  • 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 R.java: public static final int button2=0x7f060004; public static final int NewWindow=0x7f040005; • Getting resources via code(activity) Button button = (Button)findViewById(R.id.button2) String myAppName = getResources().getString(R.string.app_name); 68
  • 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
  • Working with Assets AssetManager used to manage “Assets” resources AssetManager am = activity.getAssets(); InputStream is = am.open("test.txt"); 70
  • Application Meta Data Files
  • Application metadata files Both files are generated by android proguard.cfg / proguard-project.txt - Java class file shrink, optimizer default.properties – parameters like android version 72
  • Thread
  • 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
  • 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
  • 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. http://www.aviyehuda.com/blog/2010/12/20/android-multithreading-in-a-ui-environment/ • Message also holds a data structure that can be passed back to the handler Understand looper: http://mindtherobot.com/blog/159/android-guts-intro-to-loopers-and-handlers/ http://kurtchen.com/blog/2010/08/31/get-to-understand-handler-looper-and-messagequeue/ 76
  • 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.
  • 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
  • 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 m_ProgressDialog.show(); } }; 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()) handler.post(updateUIRunnable); //postDelay / postAtTime } thrd.start(); Private Runnable updateUIRunnable = new Runnable(){ public void run(){ updateUI(); // This Code run in the main thread } 79 }
  • 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); handler.post()  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 }
  • 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). • http://www.androiddesignpatterns.com/2012/07/loaders-and-loadermanager81 background.html
  • 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
  • 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
  • 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
  • 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). • http://developer.android.com/reference/android/content/AsyncTaskLoader.html 85
  • 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
  • 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. http://www.androiddesignpatterns.com/2012/08/implementing-loaders.html 87
  • 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
  • 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
  • Service
  • 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 !!!
  • 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.
  • 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
  • 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
  • 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
  • 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).
  • Start Service after Device Reboot (not bind service !) <manifest xmlns:android=http://schemas.android.com/apk/res/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 }
  • 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 http://www.sohailaziz.com/2012/05/intentservice-providing-data-back-to.html http://www.vogella.com/articles/AndroidBroadcastReceiver/article.html
  • 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
  • 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."
  • 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
  • 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. • http://manishkpr.webheavens.com/android-aidl-example/ 102
  • 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
  • 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
  • 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
  • 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
  • Summary: • Start service - can be restart by OS , can be started after reboot, pay attention to onCreate(), onStartCommand() 107
  • Summary 108
  • 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
  • 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
  • Toast from a Thread in a service Toast can be shown only from UI Thread (Main Thread) 111
  • links • http://docs.xamarin.com/guides/crossplatform/application_fundamentals/backgrounding/part_7_android_services • http://stackoverflow.com/questions/8668125/android-how-bound-service-can-be-noticed-about-killedclient • http://developer.android.com/reference/android/app/Service.html • http://developer.android.com/guide/components/services.html 112
  • Wake Lock
  • 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
  • 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); • http://michael.theirwinfamily.net/articles/android/starting-activity-sleeping-device https://github.com/commonsguy/cwac-wakeful (WakefulIntentService ) http://developer.android.com/reference/android/os/PowerManager.WakeLock.html 115
  • Broadcast
  • 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.
  • Send broadcast 118
  • 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>
  • Register receiver dynamic (programmatically) onResume(){ registerReceiver(receiver,intentFilter); } onPause(){ unRegisterRecevier(recevier); } 120
  • 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
  • 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
  • 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
  • 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
  • Links • http://www.compiletimeerror.com/2013/03/android-broadcast-receiver-in-detail.html#.Ukxj44Z9v2B • http://www.intertech.com/Blog/using-localbroadcastmanager-in-service-to-activity-communications/ • http://www.vogella.com/articles/AndroidBroadcastReceiver/article.html 126
  • Pending Intent & Alarm Manager
  • 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
  • Why id is important 129
  • 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
  • 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
  • Persistence
  • Persistence • Android provide 3 kinds of persistence: – Shared Preferences (Properties files) – Files – Database 133
  • 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
  • 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
  • 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
  • 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
  • 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 http://sqliteman.com/ , http://cduu.wordpress.com/2011/10/03/sqlitemanager-for-android-eclipse-plugin/
  • Create & work with DB: 139
  • 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);
  • 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
  • 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
  • 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
  • SQL FTS http://blog.andresteingress.com/2011/09/30/android-quick-tip-using-sqlite-ftstables/ • 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
  • ORM • http://ormlite.com/sqlite_java_android_orm.shtml 145
  • 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
  • NoSql http://www.couchbase.com/mobile 147
  • Content Provider
  • 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://com.android.book.BookProvider/books/23 – Retrieve all books • content://com.android.book.BookProvider/books 149
  • 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
  • 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
  • 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
  • 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
  • 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
  • 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)
  • 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 • http://www.androiddesignpatterns.com/2012/07/loaders-and-loadermanagerbackground.html • http://helpmeco.de/2012/3/using-an-android-cursor-loader-with-a-content-provider 156
  • Loader with without ContentProvider ? • https://www.grokkingandroid.com/using-loaders-in-android/ • 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
  • Location-API (location data) Location API V2 Mapping-API (display location)
  • 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
  • Best performance http://developer.android.com/guide/topics/location/strategies.html Fuse Location (12:18) 160
  • 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
  • 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
  • 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
  • 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
  • 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.
  • 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
  • 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);
  • 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
  • Map API (paint the map, add icons) https://developers.google.com/maps/documentation/android/ 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
  • Usage: 170 Tutorial
  • 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
  • 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
  • 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
  • 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
  • Debug
  • 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
  • TraceView Execution timeline Why is something running on the main thread for that long? http://www.littleeye.co/ profiler analysis 177 Function statistics A call about time zones is taking this long?
  • 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(StrictMode.java:1105) 03-14 08:56:19.665: D/StrictMode(6309): at java.net.InetAddress.lookupHostByName(InetAddress.java:391) 03-14 08:56:19.665: D/StrictMode(6309): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242) 03-14 08:56:19.665: D/StrictMode(6309): at java.net.InetAddress.getAllByName(InetAddress.java:220) 03-14 08:56:19.665: D/StrictMode(6309): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137) 03-14 08:56:19.665: D/StrictMode(6309): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164) 03-14 08:56:19.665: D/StrictMode(6309): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119) 03-14 08:56:19.665: D/StrictMode(6309): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360) 03-14 08:56:19.665: D/StrictMode(6309): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555) 03-14 08:56:19.665: D/StrictMode(6309): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487) 03-14 08:56:19.665: D/StrictMode(6309): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465) 03-14 08:56:19.665: D/StrictMode(6309): at com.dori.MyAct.getHttpContent(MyAct.java:61) 178 03-14 08:56:19.665: D/StrictMode(6309): at com.dori.MyAct.onCreate(MyAct.java:38)
  • Use StrictMode 179
  • 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
  • Http Connection
  • 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
  • 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
  • Manifest Http Permission To access the Internet: android.permission.INTERNET To check the network state: android.permission.ACCESS_NETWORK_STATE. 184
  • HttpURLConnection HttpURLConnection conn = (HttpURLConnection) newURL(“www.google.com”).openConnection(); InputStream is= conn.getInputStream(); 185
  • 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
  • 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("http://example.com/hotels/{hotel}/bookings/{booking}", String.class, vars); String url = "https://ajax.googleapis.com/ajax/services/search/web?v=1.0&q={query}"; String result = restTemplate.getForObject(url, String.class, "whatever"); 187 restTemplate.getMessageConverters().add(new GsonHttpMessageConverter()); answer[] answers = restTemplate.postForObject(url, requestObject, answer[].class);
  • Rest Frameworks: • • • Crest RestEasy : resteasy-mobile RestEasy Restlet Web-Service Clients (Ksoap) 188
  • Web Server i-jetty – Install web server on android device 189
  • WebSocket http://autobahn.ws/ 190
  • 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
  • Security/Permission
  • 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
  • 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
  • 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
  • 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.
  • ProGuard http://proguard.sourceforge.net/index.html • 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 http://code.google.com/p/zxing/source/browse/trunk/android/build.xml 198
  • 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
  • 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
  • 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
  • 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
  • Lib Project
  • 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
  • Sensors
  • Supported Sensors • • • • • • • • • • • 206 Temperature Accelerometer Gravity Gyroscope Rotation Magnetic Field Atmospheric Pressure Humidity Proximity – distance (cm) between device and target object Light Example Accelerometer
  • UI
  • Links UI generator tool IDE UI tips Android UI Tools Android Design Tips Android UI Patterns http://www.androidpatterns.com/ 208
  • 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
  • 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
  • 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>
  • Dashboard 212
  • ActionBar 213
  • ActionBar (new navigation) Navigating up Example 214
  • QuickAction 215
  • 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
  • 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
  • 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
  • 9Patch • To Scale PNG images use NinePatch-PNG : specify which parts of the images cab be stretched, and provide images per resolution draw9Patch 219
  • 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
  • android:layout_weight (like % in css) for table layout similar functionality is achieved via android:stretchColumns android:shrinkColumns android:collapseColumns 221
  • Usability Tips • Login should be simple (or limited) • Minimum navigate • Your mobile is personalize , your app should be too 222
  • Admin App http://developer.android.com/guide/topics/admin/device-admin.html 223
  • UI Adapter
  • 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
  • Adapters ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,R.array.cars, 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
  • 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
  • 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 http://blog.dutchworks.nl/2009/09/17/exploring-the-world-of-android-part-2/ 228
  • Toast
  • 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 toast.show();
  • Notification
  • 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
  • Widget
  • 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
  • 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
  • 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="http://schemas.android.com/apk/res/android" android:widgetCategory="keyguard|home_screen" ... > ... </appwidget-provider> 236
  • Links http://www.vogella.com/articles/AndroidWidgets/article.html http://developer.android.com/guide/practices/ui_guidelines/widget_design.html http://developer.android.com/design/patterns/widgets.html http://developer.android.com/guide/topics/appwidgets/index.html 237
  • Custom View
  • Custom View Extend View/Layout classes and override the appropriate methods (onDraw()…) Custom/Compound views 239
  • Menu
  • Menus Option Menu - displays only icons and text for up to six Items. If more than six Menu Items have been defined, a “More” item will be added which will open Expanded Menu. Expanded Menu: • Triggered when a user selects the “More” menu item, it displays a scrollable list of only the Menu Items that weren‟t visible in the option menu. • displays full text, shortcut keys, and checkboxes/radio buttons But It does not display icons. • You cannot force Android to display the expanded menu instead of the option menu. • As a result, you should avoid assigning icons to Menu Items that are likely to appear only in the expanded menu and ensure that menu items with checkboxes or radio buttons will appear only in the 241 extended menu.
  • Menus Context menu - long click on a view component like EditText will invoke Context Menu • Context menu can include nested menus like which called SunMenu 242
  • Dialog • • • Dialog is a popup window which come on top existing screen and take the focus. (use DialogFragment) Dialog can be nested with many UI components You can also create activity layout as a dialog <activity android:name=”MyDialogActivity” android:theme=”@android:style/Theme.Dialog”> </activity> 243
  • Web/Hybrid
  • Native vs. Hybrid 245
  • WebView • Allows to display web pages • Webview allow to use javascript, html tags, handle page navigation • <a href="tel:9725123456">9725123456</a> • Google- How to load fast 246
  • Web development Develop regular Html, JS pages without interaction with the device API 247
  • Spring Mobile (Spring MVC for web mobile) 248
  • Frameworks (Gwt,PrimeFaces) http://prezi.com/embed/6ngydrtzj2ln/ (GWT-Mobile / Mgwt) http://primefaces.org/showcase/mobile/index.jsf ICEmobile 249
  • Hybrid Develop web pages that can interact with the device native API (via JS) 250
  • Hybrid = JavaScriptBridge Code Example Code Example2 251
  • PhoneGap code example navigator.camera.getPicture(onSuccess, onFail, { quality: 50, destinationType: Camera.DestinationType.DATA_URL }); function onSuccess(imageData) { var image = document.getElementById('myImage'); image.src = "data:image/jpeg;base64," + imageData; } function onFail(message) { alert('Failed because: ' + message); } 252
  • Hybrid platforms 253
  • Flash Build UI using flash – http://www.adobe.com/devnet/flash-builder/articles/hello-world.html Developing and using Adobe AIR native extensions for Android devices Phone Call example: navigateToURL(new URLRequest("tel:5555555555")); 254
  • Dev/Test tools
  • Development frameworks/tools http://androidannotations.org/ class RoboWay extends RoboActivity { @InjectView(R.id.name) TextView name; @InjectView(R.id.thumbnail) ImageView thumbnail; @InjectResource(R.drawable.icon) Drawable icon; @InjectResource(R.string.app_name) String myName; @Inject LocationManager loc; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); name.setText( "Hello, " + myName ); } } 256 @ViewById ListView bookmarkList; Backward Compatibility (Fragment): • http://nineoldandroids.com/ • http://actionbarsherlock.com/ • http://developer.android.com/tools/extra s/support-library.html
  • Mobile Analytics Google analytics Demo Activity tracking - Button click Exception tracking Ecommerce Tracking- track shopping cart transactions Cross device analytics Reports : location , carrier, OS version, visit time, unique users … 257
  • AR https://developer.vuforia.com/ http://www.junaio.com/ 258
  • Test frameworks http://www.vogella.com/articles/AndroidTesting/article.html • Monkey - command line tool which sends random events to your device. • MonkeyRunner- control an Android device or emulator from outside of Android code • UIAutomator – A Java library containing APIs to create customized functional UI tests, and an execution engine to automate and run the tests 259
  • UiAutomator(outOfApp) vs robotium(inApp): 260
  • Google Espresso Testing UI from the main thread ! ! ! http://www.youtube.com/watch?v=T7ugmCuNxDU 261
  • Hierarchy Viewer / uiAutomatorViewer uiautomatorviewer : A GUI tool to scan and analyze the UI components of an Android application. 262
  • IDE – Android Studio What's New in Android Developer Tools 263
  • PhoneGap Editor http://readwrite.com/2011/10/16/appmobicreates-xdkframework#awesm=~okSUuYMUa4lSIt 264
  • Code Generator Frameworks Write application in C++ or oriented language and compile to Android app (java) 265
  • Cloud
  • Sync (syncAdapter) http://ericmiles.wordpress.com/2010/09/22/connecting-the-dots-with-android-syncadapter/ http://www.c99.org/2010/01/23/writing-an-android-sync-provider-part-2/ 267
  • Android Push (cloud) Allow to push data from server to devices http://www.youtube.com/watch?v=YoaP6hcDctM http://www.youtube.com/watch?v=y76rjidm8cU http://code.google.com/android/c2dm/ GCM http://developer.android.com/training/cloudsync/gcm.html http://developer.android.com/google/gcm/index.html http://developer.android.com/google/gcm/gs.html http://www.vogella.de/articles/AndroidCloudToDeviceMessaging/article.html http://api.shephertz.com/cloudapidocs/guide/0.8.3/android/pushnotification_api.html 268
  • Hacking
  • Private/Internal API http://www.xda-developers.com/android/using-internalhidden-classes-of-the-android-api/ http://developer.sonymobile.com/2011/10/28/code-examples-using-hidden-android-apis/ http://devmaze.wordpress.com/2011/01/18/using-com-android-internal-part-1-introduction/ http://forum.xda-developers.com/showthread.php?t=1711653 http://blog.codetastrophe.com/2008/12/accessing-hidden-system-service-apis-in.html http://andrewoid.blogspot.co.il/2008/12/hacking-android-api.html 270
  • Best Practice
  • • http://developer.android.com/guide/practices/index.html • http://developer.android.com/training/best-performance.html 272
  • Thank u !
  • Activity Stack – The UI State is saved • When Activity „A‟ starts Activity „B‟, Activity „A‟ is stopped, but the OS save its state (such as scroll position and text entered into forms). • If the user presses the Back button within Activity B, activity B is popped from the stack and destroyed. • The previous activity in the stack (A) is resumed with its state restored. 274