274
Android Development Dori Waldman

Dori waldman android _course

Embed Size (px)

DESCRIPTION

Android course for developers from beginner to expert

Citation preview

Page 1: Dori waldman android _course

Android DevelopmentDori Waldman

Page 2: Dori waldman android _course

2

Overview Android Introduction Android Components (Activity, Intent, Fragment, Service, Broadcast receiver,

ContentProvider…)

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)

Page 3: Dori waldman android _course

Android Introduction

Page 4: Dori waldman android _course

4

Course Resources

http://developer.android.com/

http://www.xda-developers.com/category/android/

http://www.vogella.de/android.html

http://developer.android.com/training/index.html

Page 5: Dori waldman android _course

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

Introduction Native OS

Page 6: Dori waldman android _course

6

Smart Phone definition ?

• No standard (screen resolution / camera / GPS)

• More than 30 vendors (HTC, Samsung , Firefox …)

Page 7: Dori waldman android _course

7

Code Complicity

if (packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA)) { Log.i("camera", "This device has camera!"); }else{ Log.i("camera", "This device has no camera!"); }

if ( android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD) { // only for gingerbread and newer versions }

GooglePlayServicesUtil.isGooglePlayServicesAvailable()

Page 8: Dori waldman android _course

8

Same App on different devices/OS

The Pain of Native UI , or why Hybrid is poplar ?

2.3.4 Samsung 4.1 Samsung

Page 9: Dori waldman android _course

9

Mobile Web Vs Desktop Web• Web site should fit both – one development effort

Page 10: Dori waldman android _course

10

Mobile Web Vs. Desktop Web• Same functionality ?

View pictures taken nearby

No uploads

Page 11: Dori waldman android _course

11

Mobile Challenges (external app events)

• Android OS might kill the application process in case of non efficient resources therefore developer should listen to OS events (onLowMemory() …) and response to them (save the application data).

• For example • phone call during payment flow. • device rotation – will restart the application• lost internet connection during upload.

Page 12: Dori waldman android _course

12

Major Android versions • 2.3 -API Level: 9 (gingerbread)• 3.0 -API Level: 11 (honeycomb) provide support for

tablets• 4.0 -API Level: 14 (ice cream sandwich)

Page 13: Dori waldman android _course

13

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. 

Page 14: Dori waldman android _course

14

Android is not only for Phones/Tablet/Tv

Page 15: Dori waldman android _course

Android Stack

Page 16: Dori waldman android _course

16

Stack

Linux Kernel provides hardware drivers, memory/power/network/security/thread management

Page 17: Dori waldman android _course

17

File System

• User application will be located under data folder

• Framework Application will be located under System/App folder

• C++ libs will be located under system/framework folder

Page 18: Dori waldman android _course

18

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

Page 19: Dori waldman android _course

19

Android Artifact

• Android executable “.apk” file (similar to war file).

• Each app run in its own linux process

• Java classes are being convert into Dalvik executable “.dex” file (corresponding to .jar file) which are half size compare to jar file.

• 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/

Page 20: Dori waldman android _course

20

• 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)

• Hprof-conv (convert logs to preferred profile tool)

Android Tools

Page 21: Dori waldman android _course

21

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

Main Components

Page 22: Dori waldman android _course

First App

Page 23: Dori waldman android _course

23

Recommended way to develop UI

Page 24: Dori waldman android _course

24

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);

Page 25: Dori waldman android _course

25

Code Example

• EX1– Create Application with 3 activities , 2 fragments – Transfer data between activities using Intent / StartActivityForResult– Transfer data between activity and its fragments using getActivity() – Build UI programmatically/xml– Using Shared Preferences to persist and transfer data – Fragment Stack – Activity Stack– Open Activity Explicitly / Implicitly

Page 26: Dori waldman android _course

Activity

Page 27: Dori waldman android _course

27

•  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.

Activity (Activity Stack)

Page 28: Dori waldman android _course

28

Activity State:

• Active - The screen is foreground/focus

• Pause - lost focus but is still visible (another activity has focus on top of this activity), it maintains its state and remains attached to the window manager, but can be killed by the system in extreme low memory situations.

• Stop – Not visible to the user (cover by another activity) It still retains its state, it will often be killed by the system when memory is needed elsewhere.

• Finish – either by calling to finish() or when OS kill the process, When application finished, it is actually cached until OS will free cached resources

Page 30: Dori waldman android _course

30

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)

Activity Lifecycle - entire lifetime

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.

Page 31: Dori waldman android _course

31

onStart() is called after onCreate, or after onRestart() (when user navigate back to the activity)

Activity Lifecycle - visible lifetime

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…

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.

Page 32: Dori waldman android _course

32

Activity Lifecycle – foreground/focus lifetime

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.

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.

Page 33: Dori waldman android _course

33

OnSaveInstanceSave()– onRestoreInstanceState()• OS default behavior save the state of an activity in memory when it is

stopped. This way, when users navigate back to a previous activity, the view

appears the same way the user left it.• The default implementation calls the corresponding onSaveInstanceState()

method for every View in the layout (only if for views with android unique id) and saves the views state in Bundle : onCreate(Bundle) /onRestoreInstanceState(Bundle)

• For all other cases you need to save and restore the UI state via onSaveInstanceState()

• onRestoreInstanceState(Bundle) will be called by OS only if OS killed the application and restart it again.

Page 34: Dori waldman android _course

34

Example of Activity lifecycle – Demo EX1

INFO/EX1-A (406): onCreate BeginINFO/EX1-A (406): onCreate EndINFO/EX1-A (406): onStart BeginINFO/EX1-A (406): onStart EndINFO/EX1-A (406): onResume BeginINFO/EX1-A (406): onResume End

INFO/EX1-A (406): onSaveInstanceState BeginINFO/EX1-A (406): onSaveInstanceState EndINFO/EX1-A (406): onPause BeginINFO/EX1-A (406): onPause EndINFO/EX1-B (406): onCreate BeginINFO/EX1-B (406): onCreate EndINFO/EX1-B (406): onStart BeginINFO/EX1-B (406): onStart EndINFO/EX1-B (406): onResume BeginINFO/EX1-B (406): onResume EndINFO/EX1-A (406): onStop BeginINFO/EX1-A (406): onStop End

INFO/EX1-B (406): onPause BeginINFO/EX1-B (406): onPause EndINFO/EX1-A (406): onRestart BeginINFO/EX1-A (406): onRestart EndINFO/EX1-A (406): onStart BeginINFO/EX1-A (406): onStart EndINFO/EX1-A (406): onResume BeginINFO/EX1-A (406): onResume EndINFO/EX1-B (406): onStop BeginINFO/EX1-B (406): onStop EndINFO/EX1-B (406): onDestroy BeginINFO/EX1-B (406): onDestroy End

Activity A Start

Click on a buttonAnd open activity B

click on “Close“ and return to First Activity

Page 35: Dori waldman android _course

35

Example of Activity lifecycle (Ex1)INFO/EX1-A (406): onCreate BeginINFO/EX1-A (406): onCreate EndINFO/EX1-A (406): onStart BeginINFO/EX1-A (406): onStart EndINFO/EX1-A (406): onResume BeginINFO/EX1-A (406): onResume End

INFO/EX1-A (406): onSaveInstanceState BeginINFO/EX1-A (406): onSaveInstanceState EndINFO/EX1-A (406): onPause BeginINFO/EX1-A (406): onPause EndINFO/EX1-A (406): onStop BeginINFO/EX1-A (406): onStop End

Activity ‘A’ started

Get phone call, OS Destroy the Activity

Hung up and unlock Phone, back to app INFO/EX1-A (832): onCreate Begin

INFO/EX1-A (832): onCreate EndINFO/EX1-A (832): onStart BeginINFO/EX1-A (832): onStart EndINFO/EX1-A (832): onRestoreInstanceState BeginINFO/EX1-A (832): onRestoreInstanceState EndINFO/EX1-A (832): onResume BeginINFO/EX1-A (832): onResume End

INFO/EX1-A (406): onRestart BeginINFO/EX1-A (406): onRestart EndINFO/EX1-A (406): onStart BeginINFO/EX1-A (406): onStart EndINFO/EX1-A (406): onResume BeginINFO/EX1-A (406): onResume End

Page 36: Dori waldman android _course

36

http://developer.android.com/guide/topics/manifest/activity-element.html

*configChanges attribute prevent application from restart (rotate)

Activity Configuration

Page 37: Dori waldman android _course

37

Task – Task Stack (Home Button) • Task is a collection of activities that users interact with when performing a

certain job (~application)• When the user leaves a task by pressing the Home button, the current

activity is stopped and its task goes into the background.• The OS retains the state of every activity in the task. If the user later on

resumes the task by selecting the launcher icon that began the task, the task comes to the foreground and resumes the activity at the top of the stack.

• For example open SMS app and write SMS , Click on Home button and start another app, close that app , long click on Home button and select the SMS app , you will see the text that you started to wrote.

Task B receives user interaction in the foreground, while Task A is in the background, waiting to be resumed.

Page 38: Dori waldman android _course

Fragment

Page 39: Dori waldman android _course

39

Fragment• Divide Activity to reusable components, each has its own lifecycle (onCreate()

…)

• Fragment is tightly coupled to activity in which its placed, therefore when the activity is stop/pause/destroy the fragments are also stop/pause/destroy.

• Fragments are also managed in a stack

• Fragment can be added/removed several time during activity lifetime

• Its possible to create without any UI

• For backward compatibility you should extends “FragmentActivity” instead of Fragment”

Page 40: Dori waldman android _course

40

Fragment LifecycleOnAttach – bound to activity , get reference to parent activityonCreate – 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 hereonStart – visible onResume – focusonPause – end of focusonSavedInstanceState onStop – end of visibleonDestroyView – Fragment View is detached , clean UI resourcesonDestroy – clean resources , end of lifeonDetach – Fragment is detach from activity, if parent activity will be killed, this step will not be called

Page 41: Dori waldman android _course

41

Static way to add fragment

<linearLayout>

<!– FragA is a class that extends Fragment - ->

<fragment android:name=“com.dori.FragA”/>

</linearLayout>

Page 42: Dori waldman android _course

42

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();

Page 43: Dori waldman android _course

43

Fragments for both Tablet / Phones

• Each activity will convert into fragment meaning:– Create new fragments and move the activities code into it , the original activity will

act as a container for the fragment.• Create 2 kinds of layouts, the OS will select the layout according to screen size.

– One layout in layout-land folder for tablet view with fragA_layout.xml – layout per fragment fragA_layout.xml and fragB_layout.xml

• Each fragment will be created in a separated activity , Activity B is never used on a tablet. It is simply a container to present Fragment B.

• When you need to switch Fragments, activity A checks if the second fragment layout is available in his layout:– If the second fragment is there, activity A tells the fragment that it should update

itself. – If the second fragment is not available activity A starts the second activity.

Page 44: Dori waldman android _course

44

Work with Fragments

Page 46: Dori waldman android _course

46

Fragment recreation

• When activity is being destroyed and restart (Rotate) you can select that the fragment will not be restart with its associate activity, by calling setRetainInstane(true) from the Fragment onCreate()

• In that case The Fragment onDestroy() onCreate() will not be called while the attached activity is being destroyed-created , All other Fragment lifecycle methods will be invoked like onAttach…., therefore moving most of the object creation to onCreate will improve the performance

Page 47: Dori waldman android _course

Intent

Page 48: Dori waldman android _course

48

Intent• Intent is used to invoke activity/service/broadcast

– More Intents components will be explained later: • PendingIntent• ServiceIntent • Broadcast Intents

• There are 3 ways to invoke activity:Intent intent = new Intent(MyActivity.this, AnotherActivity.class);Intent.putExtra(“someLabel”, “someValue”);startActivity(intent);

Page 49: Dori waldman android _course

49

Second way to invoke Intent:

Intent intent = new Intent();intent.setComponent(

new ComponentName("com.android.contacts“, "com.android.contacts.DialContactsEntryActivity“

);startActivity(intent)

Page 50: Dori waldman android _course

50

Third way to invoke intent - Late Runtime Binding This example will start dialer activity and will make a call Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(“tel:52325”));startActivity(intent);

While this intent will only open dialer applicationnew 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)

Action Data -optional

Page 51: Dori waldman android _course

51

Activity Callback:• In order to get response back from sub activity, invoke

startActivityForResult and provide activity Id:Intent intent = new Intent(this, SubAct.class);Int subActId = 1;startActivityForResult(intent, subActId );

• Before sub-Activity is closed, call setResult to return a result(as intent) with status to the calling Activity.

Intent myIntent= new Intent();myIntent.putExtra("somethingBack",”someValue”);setResult(RESULT_OK, myIntent);finish();

Page 52: Dori waldman android _course

52

Activity Callback:

• When a sub-Activity closes, callback method will be invoked in the parent activity onActivityResult

public void onActivityResult(int requestCode,int resultCode,Intent data) {switch(requestCode) {

case (subActId) : {if (resultCode == Activity.RESULT_OK) {

data.getStringExtra(“somethingBack”)…

Page 53: Dori waldman android _course

53

Logs – callback is called before activity closed• 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

Page 54: Dori waldman android _course

54

Adding & Retrieving data from intent

Intent.putExtra(String name, boolean value); //simple value

Intent.putExtra(String name, int[] values); // simple array

Intent.putParcelableArrayListExtra(String name, ArrayList arrayList);

Intent.putExtra(Bundle bundle) // Bundle is a key-value map

Intent.putSerilaizable()

If you're just passing objects use Parcelable , It requires a little more effort to use than using Java's native serialization, but it's way faster (and I mean way, WAY faster).

intent.getExtras();

Page 55: Dori waldman android _course

55

Intent Filters• Intent Filters are used to register Activities, Services, and Broadcast

Receivers, if the intent filter attributes “match” the calling Intent (will be explained later) the action will be invoked, for Example AppA will invoke AppB:

Intent intent = new Intent(“com.dori.AnotherActivity”); // Late Runtime Binding (like open camera)

startActivity(intent);

--------------------------------------------------------------------------------------------------

<activity android:name=“SomeActivity“> // In AppB Manifest

<intent-filter>

<action android:name="com.dori.AnotherActivity"/>

<category android:name="android.intent.category.DEFAULT" />

<data …. />

</intent-filter>

</activity>

------------------------------------------------------------------------------------------

AppB will be open and , SomeActivity will be invoked

Page 56: Dori waldman android _course

56

How does android know which Intent to invoke ?• Android collect all the Intent Filters available from the installed apps, Intent

Filters that do not match the action or category associated with the Intent being resolved are removed from the list.

• If the class name attached to an intent (explicit), then every other aspect or attribute of the intent is ignored and that class will be execute, no need to continue to match the intent data.

• Otherwise we need to have a full match of action+data+category

Page 57: Dori waldman android _course

57

Sticky IntentA 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.

unregister Receiver

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.

Page 58: Dori waldman android _course

58

Send Sticky Intent

Intent intent = new Intent("some.custom.action");

intent.putExtra("some_boolean", true);

sendStickyBroadcast(intent);

….

removeStickyBroadcast(Intent intent)

Page 59: Dori waldman android _course

Manifest

Page 60: Dori waldman android _course

60

<?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” android:label=”Self Destruct” android:description=”@string/detonate_description”/>

</application>

</manifest>

Page 61: Dori waldman android _course

61

Manifest (~web.xml)• 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

Page 62: Dori waldman android _course

62

Application Class• One per application • Custom Application:Class MyApp extends Application{}And in manifest : <application android:name=“.MyApp” …>

Usage : focal point to handle events like

onLowMemory, create HttpClient,ACRA (catch app exception)

Page 63: Dori waldman android _course

Resource

Page 64: Dori waldman android _course

64

Android Project Folder• Src - A folder containing application source files

• Gen – Generated folder, don’t touch.

• Assets – resources which are not generating ID (will be explained later), assets directory can be used to store any kind of data.

Page 65: Dori waldman android _course

65

• Res – A parent folder containing the resources of the application, most of the resources are xml descriptors files.– Values - A folder containing resources like

• strings, • colors, <color name=“mycolor”>#0000000</color>• dimensions (best practice use dp or sp) <dimen name=“ex1”> 16dp

</dimen>• Style

– Drawable - A folder containing the images or xml image-descriptor files.– layout – In order to provide different layouts there is a need to create

specific folders for each configuration– xml - A folder containing additional XML files used by the application.– raw - A folder containing non xml data like audio/video files, android

compiles into binary format all the resources except the raw resources which are copied as-is into the final .apk file

– Menu - A folder containing XML-descriptor files for the menus– Anim - A folder containing XML-descriptor files for the animations.

Page 66: Dori waldman android _course

66

localization

• Use folders to support localization, orientation …. :• \res\layout\main_layout.xml • \res\layout-land\main_layout.xml• \res\layout-car\main_layout.xml //docking type• \res\values\strings.xml• \res\values-en\strings.xml

Page 67: Dori waldman android _course

67

Resources per resolution/screen sizeLayouts:Res/layout-long-land // long screen in landscape modeRes/layout-w600dp // screen width is 600 dpRes/layout-small // before android 3.2

Images folders: Res/drawable-ldpi – low density for screen with 120dpiRes/drawable-mdpi –for screen with 120dpiRes/drawable-tvdpi –213 dpiRes/drawable-hdpi – low density for screen with 240dpiRes/drawable-xhdpi – low density for screen with 320dpiRes/drawable-nodpi – force no scale regardless the device screen size

Page 68: Dori waldman android _course

68

Working with resources• Android inject the resource value at run time

(in /res/values/strings.xml) <string name=“NewWindow">myText</string>

(In /res/layout/main.xml)

<Button android:id="@+id/button2 “ android:text="@string/NewWindow“ />

• Android generate Id for each resource in 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);

Page 69: Dori waldman android _course

69

Resources Types:

• "@+id/editText1“ : my application resource , (+) means that this is a new resource , getString(R.string. editText1)

• "@android:id/button1“ , android:src="@android:drawable/star_big_on“:Android resource, getString(android.R.string. button1)

• ?android – theme support like <color:textcolor=“?android:textcolor”/>

Page 70: Dori waldman android _course

70

Working with Assets

AssetManager used to manage “Assets” resources

AssetManager am = activity.getAssets(); InputStream is = am.open("test.txt");

Page 71: Dori waldman android _course

Application Meta Data Files

Page 72: Dori waldman android _course

72

Application metadata filesBoth files are generated by androidproguard.cfg / proguard-project.txt - Java class file shrink, optimizerdefault.properties – parameters like android version

Page 73: Dori waldman android _course

Thread

Page 74: Dori waldman android _course

74

Why Threads are important

• By default the all androd components runs on the main thread (UI thread)– Activity– Service – ContentProvider– BroadcastReciver

• If any action takes more than 5 seconds, Android throws an ANR message.• In order to solve this we must manage time consuming action in a separated

thread

Page 75: Dori waldman android _course

75

Thread

Thread thread = new Thread(null,doInBackground,”background”);

Runnable doInBackground = new Runnable(){public void run(){

myBackgroundProcess();}

Q- How can I update the Main thread ?

Page 76: Dori waldman android _course

76

Thread MQ• Click on a button component is

“translate” into a message which is being dropped on to the main queue.

• Main thread listen to the main Q and process each incoming message.

• Handler are used to drop messages on the main queue usually from a separate thread.

• Message also holds a data structure that can be passed back to the handler

http://www.aviyehuda.com/blog/2010/12/20/android-multithreading-in-a-ui-environment/

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/

Page 77: Dori waldman android _course

77

Handler/Looper (message loop for a thread)

• Looper is a class that turns a thread into a Pipeline Thread (Q) 

• Handler gives you a mechanism to push tasks into it from any other threads.

– A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue.

– Each Handler instance is associated with a single thread (actually with that thread message queue) this is done during the handler creation and initialization.

– When the main thread retrieves messages, it invokes the handler that dropped the message through a callback method “handleMesage” on the handler object.

Page 78: Dori waldman android _course

78

Working with Threads

• Create a handler in the main thread.

• Create a separate thread that does the actual work. and pass it the handler

• The separate thread can do the work for longer than 5 seconds, and to send messages to the main thread by the handler.

• The messages get processed by the main thread

• The main thread will invoke the handler callback methods (the message holds reference to the handler)

Page 79: Dori waldman android _course

79

Handlerprivate Handler handler = new Handler(){ //in the main thread create Handler object

@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

}

}

Page 80: Dori waldman android _course

80

HandlerThread Start a new thread that has a looper, The looper can then be used to create handler classes

Public class MyClass implements android.os.Handler.Callback  

Public void dummy(){

// Create and start the HandlerThread - it requires a custom name

         HandlerThread handlerThread = new HandlerThread("MyHandlerThread");

         handlerThread.start();

 

          Looper looper = handlerThread.getLooper(); // Get the looper from the handlerThread

 

         Handler handler = new Handler(looper, this);

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

}

Page 81: Dori waldman android _course

81

Working with Thread API • handler - main thread getting updated by “handleMessage” callback method.

• runOnUiThread - update the main thread, from a sub thread.

• AsyncTask (android 2.2) manage the creation of the background thread and update the main thread using “onPostExecute” callback method.– AsyncTask are not persist across activity restart meaning that in case

device has been rotate the activity will be destroyed and restart and the asyncTask will be canceled, therefore its recommended to start service and in that service to run asyncTask.

• AsyncTaskLoader (android 3.0) – improve AsyncTask (data was lost across Activity configuration changes, each time the activity returns from a stopped state an refresh data call has been invoked).

• http://www.androiddesignpatterns.com/2012/07/loaders-and-loadermanager-background.html

Page 82: Dori waldman android _course

82

runOnUiThread• Thread thread = new Thread(new Runnable() { 

   public void run() {       // ...       // do long running tasks here       // … 

      // running in Activity context       runOnUiThread(new Runnable() {          public void run() {             // ...             // update UI here              // ...          }       });    } }); thread.start();

Page 83: Dori waldman android _course

83

AsyncTaskpublic 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   } } 

Page 84: Dori waldman android _course

84

Run AsyncTask

• Asynctask can be execute only once ( if you will try to run again you will get exception) meaning:

new DownloadFilesTask().execute(url1, url2, url3);

new DownloadFilesTask().execute(url4, url5, url6);

you can NOT do the following:

DownloadFilesTask dfTask = new DownloadFilesTask();

dfTask().execute(url1, url2, url3);

dfTask().execute(url4, url5, url6);

Page 85: Dori waldman android _course

85

Loader (AsyncTaskLoader)

• Loaders are responsible for – performing async tasks on a separate thread, – monitoring the data source for changes, and delivering new results to a

registered listener (usually the LoaderManager) when changes are detected. 

• Loader available within any activity/fragment via LoaderManager

• AsyncTaskLoader, CursorLoader (will be explained later). • http://developer.android.com/reference/android/content/AsyncTaskLoader.htm

l

Page 86: Dori waldman android _course

86

Use LoaderActivity/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 re-create 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)

Page 87: Dori waldman android _course

87

Create Custom Loader- Observer

Loaders should implement an observer in order to monitor the underlying data changes. When a change is detected, the observer should call Loader.onContentChanged(), which will either:

• force a new load if the Loader is in a started state • raise a flag indicating that a change has been made so that if the Loader

is ever started again, it will know that it should reload its data.

http://www.androiddesignpatterns.com/2012/08/implementing-loaders.html

Page 88: Dori waldman android _course

88

Class myLoader extends AsyncTaskLoader<T>

onStartLoading():First method which is being invoked, should invoke forceLoad()In this method you should register Observesr

loadInBackground() run in a background thread

deliverResult() Called when there is new data to deliver to the client.

The Observers will invoke myLoader.onContentChanged() correspond to data changes

Page 89: Dori waldman android _course

89

Any given Loader will either be in a started, stopped, or reset state

Loader states:

•  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).

Page 90: Dori waldman android _course

Service

Page 91: Dori waldman android _course

91

Service:• Services are background process, which has no user interface, they are used for

long running operation and also to expose functionality for external applications.

• you can update UI from service via notification/toast

• A Service is not a thread (Services by default are running on the main thread , just open a service for long time action is not enough, you must open a thread inside)

• Services run with a higher priority than inactive or invisible activities and therefore it is less likely that the Android system terminates them.

• Service which is bound to a focus activity or labeled as run in the foreground will almost never be killed – recommended not to use this option

• If the system kills your service, it restarts it as soon as resources become available again, you must design it to gracefully handle restarts by the system, depand on the service type !!!

Page 92: Dori waldman android _course

92

Lifecycle• There are 2 kinds of services:

– Started (local)- send & forget• starts it by calling startService(), • The service will run until the service or

someone else explicitly stop it stopService() or stopSelf() has been called, or in case OS need to release resources, in that case OS will restart the service.

– Bound (Remote) – • starts it by calling bindService(), does not

call onStartCommand()• return a reference onBind() to the service,

which allows to invoke the service methods from another class

• Can expose methods (aidl) to other applications.

• bound service runs only as long as another application component is bound to it, When all clients disconnect, or unbind, Android will stop that Service.

Page 93: Dori waldman android _course

93

Start Service• Start by calling

– startService(new Intent (this,MyService.class);

– startService (new Intent (MyService.PLAY_MUSIC));

• Finish by calling

– stopService() from the activity

– stopSelf() from the service class

• onCreate() will be invoked only once !

(first lunch or after OS restart it)

• OnBind might return instance or null

• onStartCommand() - this is where you will open a worker thread, called whenever a client calls startService()

• Calling startService() after the service has been started (meaning while it’s running) will not create another instance of the service, but it will invoke the service’s onStart()/onStartCommand() method again not the onCreate(),

Page 94: Dori waldman android _course

94

onStartCommand() return a flags:Start service Flags– Restart The Service

– 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

Page 95: Dori waldman android _course

95

onStartCommand() return a flags:

Start service Flags– OS Restart The Service

– 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

Page 96: Dori waldman android _course

96

Start service - IntentService

A subclass of Service which open a worker thread to handle all start requests , one at a time (Q not async not parallel like Service)

– The  onHandleIntent() - use this method to execute the background task , no need to create a new thread.

– After all received intent has been processed (onHandleIntent() returns) the service is destroyed. (no need to implement onStartCommand or onDestroy)

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).

Page 97: Dori waldman android _course

97

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);

}

}

Page 98: Dori waldman android _course

98

Getting response from start service

Updated from services will be usually using broadcast mechanism (next section)

– BroadcastReceiver – send/get data/notifications across applications, whenever you send broadcast its sent system wide

– LocalBroadcastRecevier / ResultReceiver – send/get data internal to application, Your application is the only receiver of the data

• http://www.sohailaziz.com/2012/05/intentservice-providing-data-back-to.html

• http://www.vogella.com/articles/AndroidBroadcastReceiver/article.html

Page 99: Dori waldman android _course

99

Bind Service (RemoteService= Service in a different process)

• support a Remote Procedure Call (RPC) mechanism to allow external app’s, on the same device, to connect to the service

• onBind() must return instance to the service object

• Bind service ~ the service is like a member in your app

AIDL allows to transfer objects across process’s (~intent)

• Android Interface Definition Language is used in order to define the service to other applications

• AIDL allows you to pass java primitive (char,int) , String, List, complex types (percable)

• Create AIDL file in src folder, android will generate class from the aidl file (~stub)

Page 100: Dori waldman android _course

100

Bind Service

RemoteCallbackList: "If a registered callback's process goes away, this class will take care of automatically removing it from the list. If you want to do additional work in this situation, you can create a subclass that implements the onCallbackDied(E) method."

Page 101: Dori waldman android _course

101

Reconnect bind service after service crush• onServiceDisconnected –

Called when a connection to the Service has been lost. This typically happens when the process hosting the service has crashed or been killed.

This does not remove the ServiceConnection itself , binding to the service will remain active.

Local Service:

run in the same process of the application (if app is closed the service will be closed as well) cant reconnect !

Remote Service: Service is running in separate process, when this process has crashed or been killed, only the actual service is destroyed, the activity lives in another process that bound to the service is remained, therefore you can reconnect to existing service

Page 102: Dori waldman android _course

102

Remote Service Consumer – client (RemoteServiceClient)

• Copy the AIDL file to the client application (in same package like in the service application

• Use bindService() and not startService() in order to invoke the service

• you cant assume that after calling to bindService() the service will be available !!! bindService() is asynchronous.

• When the connection to the service is established, the onServiceConnected() callback is invoked

• onServiceDisconnected() callback does not get invoked when we unbind from the service, It is only invoked if the service crashes.

• http://manishkpr.webheavens.com/android-aidl-example/

Page 103: Dori waldman android _course

103

Bind Service new flags

• BIND_ADJUST_WITH_ACTIVITY- set the service priority according to the bound activity• BIND_ABOVE_CLIENT / BIND_IMPORTANT – set the priority to as forground• BIND_NOT_FORGROUND

Page 104: Dori waldman android _course

104

Service – Process <service android:name="MyService" android:icon="@drawable/icon“ android:label="@string/service_name" android:process=":my_process" > </service>

• Usually you will not add android:process, unless the service is remote (android:process=":remote“)

• Running a service in its own process gives it its own memory address space and a garbage collector of the virtual machine.

• Even if the service runs in its own process you need to use asynchronous processing (Thread) to perform network access.

Page 105: Dori waldman android _course

105

Mixed Service (Start & bind service)

• Implements both: onStartCommand() to allow components to start it and onBind() to allow binding.

• Mixed mean that OS will keep the service running as long as its not explicitly stopped or there are no client bound to it.

• The hybrid approach is very powerful and common way to use Services:

let’s say we are writing an app that tracks user location. We might want the app to log locations continuously for later use, as

well as display location information to the screen while the app is in use. If you will only bind the service during application launch, you

will get the location update, but when the application will close the service will be destroyed as well , therefore you should also use start service approach in order to verify that the server will remain running until it will explicitly close.

Page 106: Dori waldman android _course

106

The Service will block the calling Activity until the service is started

Block UI thread ?

• The best way in this case is to start a new thread and then call a service from there.

• Intentservice is a another solution

Page 107: Dori waldman android _course

107

Summary:

• Start service - can be restart by OS , can be started after reboot, pay attention to onCreate(), onStartCommand()

Page 108: Dori waldman android _course

108

Summary

Page 109: Dori waldman android _course

109

Service – External Permission

• “android:exported = false” determine whether or not other applications can invoke the service or interact with it.

• like an activity, a service can define intent filters which allow other components to invoke the service using implicit intents, If you plan on using your service locally (other applications will not be able to use it), then you should not add intent Filters

• android:exported Default value is false if there are no intent filter, and true if there are.

• There are more flags like : FLAG_GRANT_READ_URI_PERMISSION

Page 110: Dori waldman android _course

110

Set service as Foreground• Start service can set its priority as foreground by calling

startForeground(notification_id,notification) – foreground services are expected to have interaction with the user (like player service)– This is not recommended as the OS will not kill the service and will make it

hard to recover from resource starvation situations.

• bindService(intent,connection,Flag) can use its flag to set its priority like BIND_IMPORTANT which is similar to Forground

• If there are clients bound to the service, and one of its clients is visible to the user, then the service itself is considered to be visible.

Page 111: Dori waldman android _course

111

Toast can be shown only from UI Thread (Main Thread)

Toast from a Thread in a service

Page 113: Dori waldman android _course

Wake Lock

Page 114: Dori waldman android _course

114

WakeLock & Service

• In case device is sleeping (screen not in use) and service needs to restart ,it require the device to be a wake

//acquire a WakeLock:PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);

PowerManager.WakeLock wakeLock = pm.newWakeLock(pm.SCREEN_DIM_WAKE_LOCK, "My wakelook");

// This will release the wakelook after 1000 mswakeLock.acquire(1000); // Alternative you can request and / or  release the wakelook via:// wakeLock.acquire(); wakeLock.release();

Page 115: Dori waldman android _course

115

Wake from activity

Another way

• 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

Page 116: Dori waldman android _course

Broadcast

Page 117: Dori waldman android _course

117

Receiver:

Android support event-driven application:

• Sender Application call to sendBroadcast(intent) which is asynchronous

• applications can register to those intents or system events (SMS,Low memory) by extending BroadcastReceiver

• We should avoid long running tasks in Broadcast receivers. For any longer tasks we can start a service from within the receiver.

• Broadcast are used to restart service after device reboot, update activity from a service

• Security - Make the broadcast receiver unavailable to the external applications using android:export=”false”. Otherwise other applications can abuse them.

Types:

– BroadcastReceiver – send data/notifications across system wide applications,

– LocalBroadcastRecevier / ResultReceiver – send data internal to application.

Page 118: Dori waldman android _course

118

Send broadcast

Page 119: Dori waldman android _course

119

Register receiver – static (manifest)

Intent intent = new Intent(GET_MESSAGE); // late Banding

sendBroadcast(intent);

Class ReceiverClient extends BrodcastReceiver {

@override Public void onReceive(Context context, Intent intent){

// run on main thread . . . (context can be use to start activity/service…)

}

• Manifest :

<receiver android:name=".ReceiverClient">

<intent-filter>

<action android:name="com.dori.getMessage" />

</intent-filter>

</receiver>

Page 120: Dori waldman android _course

120

Register receiver dynamic (programmatically)

onResume(){

registerReceiver(receiver,intentFilter);

}

onPause(){

unRegisterRecevier(recevier);

}

Page 121: Dori waldman android _course

121

LocalBroadcastManager• Used to register and send broadcasts of Intents within your process. This is faster and more

secure as your events don't leave your application.

LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(“WOW”)); - Send

In Activity:

private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {

@Override public void onReceive(Context context, Intent intent) {

. . .

}

@Override public void onResume() { //register

LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, new IntentFilter(“WOW"));

}

@Override protected void onPause() { // Unregister since the activity is not visible LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);

}

Page 122: Dori waldman android _course

122

Page 123: Dori waldman android _course

123

Working with Broadcast

– By registering a Broadcast Receiver, application can listen for broadcast Intents that match specific filter criteria.

– broadcast message can be received by more than one receiver (Receiver)

– Broadcast receiver has 10 sec’ to do action till application will throw ANR message (application not responding) unlike activity which has 5 seconds

– By default run on the main thread

– Broadcast Receivers will automatically start application to respond to an incoming Intent.

• As of Android 3.1 the Android system will by default exclude all BroadcastReceiver from receiving intents if the corresponding application has never been started by the user.

– Unlike a service, a broadcast receiver cant be restarted

Page 124: Dori waldman android _course

124

Long run receiver

Example: If you want a receiver that will listen to incoming SMS and will handle SMS which comes from specific location:

1. Acquire a wakelock in the receiver (listen also to BOOT_COMPLETED)

2. start service from the receiver (in case process will be shut down to clean resources, service will restart)

3. Start a separate thread from the service (avoid the 5sec limit of main thread)

4. The background thread will post a message through a handler back to the service

5. The background thread will update the service to stop itself either directly or through a handler

6. Have the service release the wake lock

Page 125: Dori waldman android _course

125

Broadcast advanced

• Normal broadcasts (sent with Context.sendBroadcast) are completely asynchronous. All receivers of the broadcast are run in an undefined order, often at the same time.

• Ordered broadcasts (sent with Context.sendOrderedBroadcast) are delivered to one receiver at a time. As each receiver executes in turn (Q), it can propagate a result to the next receiver, or it can completely abort the broadcast so that it won't be passed to other receivers. The order receivers run in can be controlled with the android:priority attribute of the matching intent-filter.

• sendStickyBroadcast (intent) – – A normal broadcast Intent is not available anymore after is was send and processed by the

system. Perform a sendBroadcast(Intent) that is "sticky," meaning the Intent you are sending stays around after the broadcast is complete, so that others can quickly retrieve that data through the return value of registerReceiver(BroadcastReceiver, IntentFilter), by register to sticky event you don’t need to wait for next event to be trigger in order to get the data (Battery level)

Page 127: Dori waldman android _course

Pending Intent & Alarm Manager

Page 128: Dori waldman android _course

128

Pending Intent

• Android allows a component to store an intent for future use by wrapping intent with PendingIntent .

• A PendingIntent is an intent that you give to another application (Notification Manager, Alarm Manager, or other 3rd party applications), which allows the foreign application to use your application's permissions to execute a predefined piece of code, on your behalf, at a later time.

• If you give the foreign application an Intent, they will execute the Intent with their own permissions. But if you give a PendingIntent , that application will execute the contained Intent using your permission.

• To get PendingIntent you will not use C’tor (Android manage pool of PendingIntent)– PendingIntent.getActivity(context, requestCode, intent, flags)//start activity – PendingIntent.getService(context, requestCode, intent, flags) //start service– PendingIntent.getBroadcast(context, requestCode, intent, flags) // call broadcast receiver

flag indicates what to do if there is an existing pending intent – whether to cancel it, overwrite its extra data..

request code/id is used to distinguish two pending intents when their underlying intents are the same.

For example AlarmManager will invoke the last call in case you will use pending intent with same Id, but if you will use different Id then AM will invoke all calls

Page 129: Dori waldman android _course

129

Why id is important

Page 130: Dori waldman android _course

130

Alarm Manager (Scheduler)

• Used to trigger event at specific time or schedule EVEN IF THE APPLICATION IS CLOSED. They are managed outside of the application scope.

• If the application is running it probably be better to invoke timer tasks with Timer/Threads/Background services.

• Usage:

• get Alarm Manager instance• Provide to the Alarm Manager, PendingIntent which will be caught by the

receiver

One time: alarmManager.set(AlarmManager.RTC_WAKEUP, firstTime, pendintIntent);

Repeat : am.setRepeating(AlarmManager.RTC_WAKEUP, firstTime, 5*1000, pendintIntent);//every 5 sec

Page 131: Dori waldman android _course

131

Alarm Manager Flags:

– RTC_WAKEUP • wake the device from sleep in order to fire the intent

– 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

– ELAPSED_REALTIME_WAKEUP • wake the device and fire intent after amount of time has passed since device has

been reboot

Page 132: Dori waldman android _course

Persistence

Page 133: Dori waldman android _course

133

Persistence

• Android provide 3 kinds of persistence:– Shared Preferences (Properties files)– Files– Database

Page 134: Dori waldman android _course

134

Shared Preferences (properties files)– Fast & Easy Persistent mechanism – Support for primitive ,Boolean, string, float, long, and integer– Can be private to the application or global(shared) to all applications

• Preferences files located at (emulator) : data/data/<package name>/shared_pref/<preferences name>

SharedPreferences preferences = getSharedPreferences("myPref", MODE_PRIVATE);preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

Editor editor = preferences.edit();editor.putString("mykey", “mayValue”);editor.commit(); //in activity A

preferences.getInt("mykey", “defaultValue”) // in activity B

Page 135: Dori waldman android _course

135

Shared Preferences – UI (select option from list)• Android provide built-in UI preferences classes like : CheckBoxPreference ,

EditTextPreference, PreferencesActivity, those object has onSharedPreferencesChangeListener for ui changes.

Page 136: Dori waldman android _course

136

The ‘Activity’ Special Shared Preferences• Activity.getPreferences(Mode.Private) without specify name – this is used to

save activity preferences which are not shared with other objects in the application.

• Bundle in onCreate(bundle)/ onSaveInstanceState(bundle) , onRestoreInstantState(bundle) is a private case of shared preferences that will not be share among other activities in the same application, this is used to persist UI state in case OS terminate the activity and restart it like Rotate device.

Page 137: Dori waldman android _course

137

Files

// private file associated with this Context's application package FileOutputStream fos = openFileOutput(FILE_NAME, Context.MODE_PRIVATE);

FileInputStream fis = openFileInput(FILE_NAME);

• File Management Tools :

– DeleteFile– FileList – array with all files name which has been created by the

application

Page 138: Dori waldman android _course

138

Database (SqlLite)

• SqlLite is an relational database that comes with android– stored at /data/data/<package_name>/databases (visible from emulator)– By default, all databases are private, accessible only by the application that

created them. – To share a database across applications, use Content Providers– Android save database version and compare it during app upgrade in order

to verify it DB needs to rebuild.

– GUI tool http://sqliteman.com/ , http://cduu.wordpress.com/2011/10/03/sqlitemanager-for-android-eclipse-plugin/  

Page 139: Dori waldman android _course

139

Create & work with DB:

Page 140: Dori waldman android _course

140

SqlLite:• sqlLiteOpenHelper object used to manage the logic of create/update DB/TableThis 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 ,// fromcolumns, //Which columns to return like new String[]

{FIRST_COLUMN,SECOND_COLUMN};

selection, // select criteriaselectionArgs, //criteria values

groupby,having,order);

Page 141: Dori waldman android _course

141

Working with cursor

• You need to use moveToFirst() because the cursor is positioned before the first row.

• The cursor can move forward and backward.

if (cur.moveToFirst() == false)}//no rows empty cursorreturn;

{while(cur.moveToNext())} //cursor moved successfully //access fields{

Page 142: Dori waldman android _course

142

Working with cursor

All field-access methods are based on column number, so you must convert the column name to a column number first :

• You need to know the column names : int column_Index=cur.getColumnIndex(“age”); //2

• You need to know the column types : int age = cursor.getInt(column_Index) //30

• ContentValues objects are used to insert new rows into tablesContentValues contentValues = new ContentValues();contentValues.put("name", person.getName());contentValues.put("age", person.getAge());db.insert(DATABASE_TABLE, null, contentValues);

Page 143: Dori waldman android _course

143

Cursor usage

• it’s strongly recommended that all tables include an auto increment key field called “_id” which is mandatory for contentProvides which represents the row ID.

Page 144: Dori waldman android _course

144

http://blog.andresteingress.com/2011/09/30/android-quick-tip-using-sqlite-fts-tables/

SQL FTS

• If your data is stored in a SQLite database on the device, performing a full-text search (using FTS3, rather than a LIKE query) can provide a more robust search across text data and can produce results significantly faster.

• FTS = creating virtual tables which in fact maintain an inverted index for full-text searches

Page 145: Dori waldman android _course

145

ORM

• http://ormlite.com/sqlite_java_android_orm.shtml

Page 146: Dori waldman android _course

146

ViewBinder

• Use it In case you need to change the display format of the values fetched by cursor (different display for dateTime)

• Cursor.setViewBinder()

Page 147: Dori waldman android _course

147

http://www.couchbase.com/mobile

NoSql

Page 148: Dori waldman android _course

Content Provider

Page 149: Dori waldman android _course

149

Content Provider

• Content Provider are used to share data among applications without exposing the storage layer (for example retrieve contact list)

• Access to Content Providers is handled by the ContentResolver (query, insert, update, delete)

• Syntax is REST-like URIs, – Retrieve a specific book (23)

• content://com.android.book.BookProvider/books/23– Retrieve all books

• content://com.android.book.BookProvider/books

Page 150: Dori waldman android _course

150

ContentProvider require to Manage the Cursor • startManagingCursor(cursor) –

– Manage the Cursor lifecycle within your Activities.• When the activity terminates, all managed cursors will be closed. • when the activity is paused, it will automatically deactivate the cursor. • Invoke requery() on the cursor each time the activity returns from a

stopped state

• managedQuery– A wrapper around the ContentResolver's query() +

startManagingCursor(cursor)– performs a query on the main UI thread

using ContentResolver's query() require to manage the Cursor (startManagingCursor)

Page 151: Dori waldman android _course

151

ContentProvider - queries

• Example:

Uri contacts_uri = Contacts.People.CONTENT_URI; (android built in provider)

string[] projection = new string[] {People._ID,People.NAME,People.NUMBER{;

Cursor managedCursor = getContentResolver (). managedQuery(

contacts_uri, //URI

projection, //Which columns to return.

“id=“, // WHERE clause

new String[] {23} , // where values

Contacts.People.NAME + " ASC"); // Order-by clause.

Page 152: Dori waldman android _course

152

ContentProvider – queries (/23)

• Example:

Uri contacts_uri = Contacts.People.CONTENT_URI; (android built in provider)

Uri myPersonUri = peopleBaseUri.withAppendedId(contacts_uri , 23);

string[] projection = new string[] {People._ID,People.NAME,People.NUMBER{;

Cursor managedCursor = getContentResolver (). managedQuery (

myPersonUri , //URI in this example its already include where people.Id=23

projection, //Which columns to return.

null, // WHERE clause

null, // where values

Contacts.People.NAME + " ASC"); // Order-by clause.

• Demo (Ex8 –must create 2 contacts person before)

Page 153: Dori waldman android _course

153

ContentProvider – add new data

• Adding new entry

ContentValues values = new ContentValues();

values.put("title", "New note");

values.put("note","This is a new note");

ContentResolver contentResolver = activity.getContentResolver();

Uri uri = contentResolver.insert(Notepad.Notes.CONTENT_URI, values);

This call returns a URI pointing to the newly inserted record

Page 154: Dori waldman android _course

154

Create custom Content Provider

– Extend the abstract class ContentProvider.

– Implement methods: query, insert, update, delete, and getType.

– Register the provider in the manifest file.

– Example

Page 155: Dori waldman android _course

155

It’s a loader that queries the ContentResolver and returns a Cursor

CursorLoader (3.0+)

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.

     updateView(null)

  }

Page 156: Dori waldman android _course

156

Why Use Loader ?

• CursorLoader handle cursor lifetime , instead of to use manageQuery , startManagingCursor– Requery() will invoke only when underline data has been changed , (activity

restart will not trigger it)– all cursor operations are done asynchronously, main thread is safe.

• No need to implement Observer , has cursorLoader observer any data changes

• http://www.androiddesignpatterns.com/2012/07/loaders-and-loadermanager-background.html

• http://helpmeco.de/2012/3/using-an-android-cursor-loader-with-a-content-provider

Page 157: Dori waldman android _course

157

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.

Page 158: Dori waldman android _course

Location APIV2

Location-API(location data)

Mapping-API(display location)

Page 159: Dori waldman android _course

159

Location providers:• GPS:

– is most accurate, – it only works outdoors, – it quickly consumes

battery power, – doesn't return the

location as quickly as users want.

• Network Location Provider determines user location using cell tower and Wi-Fi signals

– providing location information in a way that works indoors and outdoors,

– responds faster, – uses less battery power.

Page 160: Dori waldman android _course

160

Best performance

http://developer.android.com/guide/topics/location/strategies.html

Fuse Location (12:18)

Page 161: Dori waldman android _course

161

Location API

• Depending on the device, there may be several technologies (Location Provider) to determine the location.

• You cant assume that GPS for example will be available on all devices or that

its already enable when you will use it.

• Location Provider, can offer different capabilities like power consumption, accuracy, the ability to determine altitude, speed, distanceBetween()

Page 162: Dori waldman android _course

162

New One 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.

new location api

Page 163: Dori waldman android _course

163

Getting Location details (old API)

Location location = locationManager.getLastKnownLocation(provider)• Return the last known location, Location object hold all information from

provider like speed...

• If the device has not recently updated the current location may be out of date!!!

• To get updates when location has been changed use locationManager.requestLocationUpdates(provider, 9000,200,locationListener); best practice to minimize update call by time/distance like in the example : 9 seconds, 200 meters

• To stop location updates:locationManager.removeUpdates(myLocationListener);

Page 164: Dori waldman android _course

164

Get Provider (old API)

• LocationProvider.getProvider(providerName) is used to specify which provider you want like GPS

• Another option is specify the requirements (criteria) that a provider must meet and let Android return the best provider to use.

Criteria criteria = new Criteria();

criteria.setAccuracy(Criteria.ACCURACY_COARSE);

criteria.setPowerRequirement(Criteria.POWER_LOW);

criteria.setAltitudeRequired(false);

criteria.setBearingRequired(false);

criteria.setSpeedRequired(false);

criteria.setCostAllowed(true);

String bestProvider = locationManager.getBestProvider(criteria, true);

Page 165: Dori waldman android _course

165

Proximity (old API) – GeoFencing (new API) • 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.

Page 166: Dori waldman android _course

166

Projection (Screen to GeoPoint)Translate between latitude/longitude coordinates (stored as GeoPoints) and x/y screen pixel coordinates (stored as Points).

When user click on the screen you will probably want to know the geo location coordinates of the user click• GoogleMap.OnMapClickListener (onMapClick(LatLng point))

• Projection proj = mMap.getProjection();Point startPoint = proj.toScreenLocation(new LatLng(-31.952854,

115.857342));LatLng myLat= proj.fromScreenLocation(startPoint)

// Android 2.0 code Projection projection = mapView.getProjection();projection.toPixels(geoPoint, myPoint); //to screen cordsprojection.fromPixels(myPoint.x, myPoint.y); //to GeoPoint

Page 167: Dori waldman android _course

167

Geocoder (Address to GeoPoint)• Translate between street addresses and longitude/latitude map coordinates

(contextualized using a locale) • Return a list of Address objects. Which contain several possible results, up to a

limit you specify when making the call• Geocoder lookups should be perform in separate thread• The accuracy and granularity of reverse lookups are entirely dependent on the

quality of data in the geocoding database; as such, the quality of the results may vary widely between different countries and locales.

• if no matches are found, null will be returned.

Geocoder geocoder = new Geocoder(getApplicationContext(),Locale.getDefault());

List<Address> addresses = geocoder.getFromLocation(latitude, longitude, number_of_results);

String streetAddress = “160 Riverside Drive, New York, New York”;

List<Address> result =geocoder.getFromLocationName(aStreetAddress, number_of_results);

Page 168: Dori waldman android _course

168

Permission

• Adding permission to the manifest:<uses-permission android:name=”android.permission.ACCESS_FINE_LOCATION”/> - GPS<uses-permission android:name=”android.permission.ACCESS_COARSE_LOCATION”/> - Network

• You cant assume that the GPS/WIFI are enable you need to check in code locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)

With new API you need to check that GoogleServices are used)

• In order to open location settings screenstartActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS), 0);

Page 169: Dori waldman android _course

169

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)

Page 171: Dori waldman android _course

171

MapFragment (recommended)• MapFragment is a subclass of the Android Fragment class, allows you to

place a map in an Android Fragment. • MapFragment objects act as containers for the map, and provide access to

the GoogleMap object.

• SupportMapFragment class (API -12 backward compatibility)

Page 172: Dori waldman android _course

172

MapView

• MapView is a subclass of the Android View class, allows you to place a map in an Android View.

• MapView acts as a container for the Map, exposing core map functionality through the GoogleMap object.

• Users of this class must forward all the life cycle methods from the Activity or Fragment containing this view to the corresponding ones in this class (onCreate()…)

Page 173: Dori waldman android _course

173

Overlay

A Ground overlay - an image that is fixed to a map

A Tile Overlay is a set of images which are displayed on top of the base map tiles. These tiles may be transparent, allowing you to add features to existing mapsunlike other overlays, if the map is recreated, tile overlays are not automatically restored and must be re-added manually.

Page 174: Dori waldman android _course

174

Mapping API (api version1 )MapView – Map Layout supports several modes: map, street view, satellite, and trafficMapActivity - Special activity which handle map activitiesMapController 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.

Page 175: Dori waldman android _course

Debug

Page 176: Dori waldman android _course

176

Debug

log messages:• Log.i(“tag”,”message”);

Trace File:Create log files that give details about an application, such as a call stack and start/stop times for any running methods.• Debug.startMethodTracing(“myFile”) - create a trace file

mnt/sdcard/myFile.trace (put in onCreate() and stopMethodTracing , in onStop(), don’t put in onDestroy())

• Use TraceView from DDMS (or run it as standalone utility) to view the result

Page 177: Dori waldman android _course

177

TraceView

Execution timeline Function statistics

Why is something running on the main thread for that long?

A call about time zones is taking this long?

http://www.littleeye.co/profileranalysis

Page 178: Dori waldman android _course

178

StrictModeReport 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)

03-14 08:56:19.665: D/StrictMode(6309): at com.dori.MyAct.onCreate(MyAct.java:38)

Page 179: Dori waldman android _course

179

Use StrictMode

Page 180: Dori waldman android _course

180

Adb debug commands

• Debug.dumpHprofData -Dump "hprof" data

• Debug.dumpService -Get a debugging dump of a system service by name

• Adb shell dumpsys - gives a wealth of information about the applications on the phone, and the current state of the phone

• adb bugreport -Prints dumpsys, dumpstate, and logcat.

Page 181: Dori waldman android _course

Http Connection

Page 182: Dori waldman android _course

182

Http Clients:

• HttpURLConnection • Apache HTTP Client

• DefaultHttpClient  - Default implementation of an HTTP client• AndroidHttpClient - Implementation of the Apache

DefaultHttpClient that is configured with reasonable default settings and registered schemes for Android.

Both support HTTPS, streaming uploads and downloads, configurable timeouts, IPv6 and connection pooling.

• Best practice is to create one instance of HttpClient for the application (in the application object)

Page 183: Dori waldman android _course

183

Which client is best?

Apache HTTP client has fewer bugs on Eclair and Froyo. It is the best choice for these releases.

From Gingerbread HttpURLConnection is the best choice.

“New applications should use  HttpURLConnection it is where we will be spending our energy going forward.”

Page 184: Dori waldman android _course

184

Manifest Http Permission

To access the Internet: android.permission.INTERNET 

To check the network state: android.permission.ACCESS_NETWORK_STATE.

Page 185: Dori waldman android _course

185

HttpURLConnection

HttpURLConnection conn = (HttpURLConnection) newURL(“www.google.com”).openConnection();InputStream is= conn.getInputStream();

Page 186: Dori waldman android _course

186

Apache Http Client

HttpClient client = new DefaultHttpClient();---------------------------------------------------------------------------------HttpGet request = new HttpGet();request.setURI(new URI("http://myWebSite?param=value"));HttpResponse response = client.execute(request);---------------------------------------------------------------------------HttpPost request = new HttpPost(http://myWebSite); List<NameValuePair> params = new ArrayList<NameValuePair>();params.add(new BasicNameValuePair(“param", "value"));UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params );request.setEntity(formEntity);HttpResponse response = client.execute(request);

Page 187: Dori waldman android _course

187

Rest:• Google-IO – REST App Development GuideLines

• RestTemplate , examplesRestTemplate 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");

restTemplate.getMessageConverters().add(new GsonHttpMessageConverter());

answer[] answers = restTemplate.postForObject(url, requestObject, answer[].class);

Page 189: Dori waldman android _course

189

Web Server

i-jetty – Install web server on android device

Page 190: Dori waldman android _course

190

WebSockethttp://autobahn.ws/

Page 191: Dori waldman android _course

191

VolleyEasy, 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 requestQ3- The response is in the Main Thread

Page 192: Dori waldman android _course

Security/Permission

Page 193: Dori waldman android _course

193

Application Signature

Android applications have to be signed with a digital certificate. upgrade application can be allowed only if it contain same signature, If you sign the application with a different signature, Android treats them as two different applications.

Android tests the certificate’s expiration only at install time. Once application is installed, it will continue to run even if the certificate expires But update will not be allowed in case application certificate expires.

Page 194: Dori waldman android _course

194

Application signing involves 3 steps:

• generate a certificate using the keytool

• using the jarsigner tool to sign the .apk file with the signature of the generated certificate

• Use zipAlign to minimize memory resources

Page 195: Dori waldman android _course

195

Page 196: Dori waldman android _course

196

Application signing steps:

• Create a folder to hold the keystore, for example c:\android\release\keytool -genkey -v -keystore "c:\android\release\release.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:\android\release\release.keystore -storepass password - keypass password C:\android_export_app\geocoder.apk testAlias

(In order to create x.apk file: right-clicking an Android project in Eclipse selecting Android Tools selecting Export Unsigned Application Package)

Page 197: Dori waldman android _course

197

ZipAlign

• If the application contains uncompressed data like images Android can map this data in the memory, But the data must be aligned on a 4-byte memory

• zipalign tool, moves uncompressed data not already on a 4-byte memory boundary to a 4-byte memory boundary

• 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.

Page 198: Dori waldman android _course

198

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

Page 199: Dori waldman android _course

199

uses-permission – During App Installation<uses-permission android:name="android.permission.INTERNET“/>

<uses-permission android:name="android.permission.READ_PHONE_STATE“/>

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE“ />

<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE“/>

<uses-permission android:name="android.permission.READ_CONTACTS" />

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Page 200: Dori waldman android _course

200

Permission - (permission + permissionClient apps) Using permission to protect resources<permission android:protectionLevel="normal“ android:name="com.myPermission“/>

MyAct activity should be launched only by applications which have the “com.myPermission” permission

<activity android:name=".MyAct“ android:label="@string/app_name" android:permission="com.myPermission"></activity>

Add to the client application (permissionClient , will open permission application)<uses-permission android:name="com.myPermission"></uses-permission>

Page 201: Dori waldman android _course

201

URI permissions• Each application run within a separate process, which has a unique and

permanent user ID (assigned at install time),this prevents one application from having direct access to another’s data

Partial permission: • In case you need to provide access finer than all or nothing,for example in case

you need to show incoming emails but not their attachments • This is where URI permissions come in:

• When invoking another activity and passing a URI, your application can specify that it is granting permissions to the URI being passed, By grantUriPermission() method and passing flag:

Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION

Page 202: Dori waldman android _course

202

Packaging - UserId• Each .apk file is uniquely identified by its root package name like

“com.dori.test” which is specified in its manifest file, The package name is tied to the application signature

• Android uses the package name as the name of the process under which to run the application, By default each package runs in its own process

• User Id: Android allocates a unique user ID for each package process. The id is used as an ID for the underlying Linux OS

• “shared user ID” allow applications to share data and even run in the same process

Add in manifast: sharedUserId="com.test.mysharedusrid“After adding it in the manifest you can use createPackageContext() which will return the context for the other application • Context targetContext = createPackageContext(“com.dori.test”, flag)

targetContext.getResources();

Page 203: Dori waldman android _course

Lib Project

Page 204: Dori waldman android _course

204

Library Projects (~jar with android context)• A library project is an android project which does not create a apk file

• Maven genarete apkLib , while Gradle generate .AAR (android archive)

Page 205: Dori waldman android _course

Sensors

Page 206: Dori waldman android _course

206

Supported Sensors

• Temperature• Accelerometer• Gravity• Gyroscope• Rotation• Magnetic Field• Atmospheric Pressure• Humidity• Proximity – distance (cm) between device and target object• Light• Example Accelerometer

Page 207: Dori waldman android _course

UI

Page 209: Dori waldman android _course

209

Android special Views

Surface View can be drawn from background thread but this option cost in memory

usage.use with caution (when you need rapid updating the UI view

(animation)).

ViewStubis 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)

Page 210: Dori waldman android _course

210

Theme

Holo Light Holo Dark Holo Light with dark action bars

<activity android:theme="@android:style/Theme.Translucent"> built in Theme (background to be transparent)

Page 211: Dori waldman android _course

211

Use style (~ css)

<?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>

<TextView

    style="@style/CodeFont"    android:text="@string/hello" /> <TextView

    android:layout_width="fill_parent"    android:layout_height="wrap_content"    android:textColor="#00FF00"    android:typeface="monospace"    android:text="@string/hello" />

Page 212: Dori waldman android _course

212

Dashboard

Page 213: Dori waldman android _course

213

ActionBar

Page 214: Dori waldman android _course

214

ActionBar (new navigation)

Navigating up Example

Page 215: Dori waldman android _course

215

QuickAction

Page 216: Dori waldman android _course

216

What is DP ? DP purpose is to remain the “same” UI element size from the user's point of view, regardless the screen resolution.

android resolution

Page 217: Dori waldman android _course

217

Scale UI Elements• When you define height/width UI element like Button its recommended not to use

specific dimensions , use match_parent / wrap_content, • If you cant , Use sp or dp:

• Dp (density independent pixels) – use this for non text elements • Sp (scale) – like dp but it is also scaled according to the user's font size

preference. use this unit for font sizes, so they will be adjusted for both the screen

density and user's preference. • Px (not recommended !!!) px = dp * (dpi / 160).

scaleing is according to the space available and screen density.

<support-screens android:smallScreens=“false” android:normalScreens=“true” android:requiersSmallestWidthDp=480 />

Page 218: Dori waldman android _course

218

Support multiple screens

Android divides the range of actual screen sizes and densities into: • Categories sizes: small, normal, large, and xlarge • Categories densities: LDPI (low), MDPI (medium), HDPI (high), and XHDPI

(extra high)

To optimize application's UI its recommended to designing layouts/bitmap images per screen size.

Page 219: Dori waldman android _course

219

9Patch

• To Scale PNG images use NinePatch-PNG : specify which parts of the images cab be stretched, and

provide images per resolution

draw9Patch

Page 220: Dori waldman android _course

220

Gravity:

• android:layout_gravity is the Outside gravity of the view (relative to the parent)

• android:gravity is the Inside gravity of that View (its content alignment)

Combination is supported: android:layout_gravity="center_horizontal|bottom"

Page 221: Dori waldman android _course

221

android:layout_weight (like % in css)

for table layout similar functionalityis achieved via android:stretchColumnsandroid:shrinkColumnsandroid:collapseColumns

Page 222: Dori waldman android _course

222

Usability Tips• Login should be simple (or limited)• Minimum navigate• Your mobile is personalize , your app should be too

Page 223: Dori waldman android _course

223

Admin App

http://developer.android.com/guide/topics/admin/device-admin.html

Page 224: Dori waldman android _course

UIAdapter

Page 225: Dori waldman android _course

225

Adapter

• Adapter are used to bind Data to Views.• They are responsible for creating the child views• Any data modification will cause the view to be updated • You need to create just one row layout that will be repeat for all rows

• Support Functionality like scrolling, click on row.• Basic adapters are :

• ArrayAdapter• SimpleCursorAdapter

Page 226: Dori waldman android _course

226

AdaptersArrayAdapter<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.

Page 227: Dori waldman android _course

227

Custom Adapters (ViewHolder pattern)In case you want to manage the display of child views: Create custom adapter by extending BaseAdapterViewHolder 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

Page 228: Dori waldman android _course

228

How we can improve performance ?

http://blog.dutchworks.nl/2009/09/17/exploring-the-world-of-android-part-2/

• 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

Page 229: Dori waldman android _course

Toast

Page 230: Dori waldman android _course

230

Toast

• Show message on top application Toast.makeText(this,“myText”, Toast.LENGTH_LONG).show();

• Create custom toast: Toast toast = new Toast(getApplicationContext());toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);toast.setDuration(Toast.LENGTH_LONG);toast.setView(layout); // some layouttoast.show();

Page 231: Dori waldman android _course

Notification

Page 232: Dori waldman android _course

232

Notification• Notifications let you notify users without interrupting their current Activities. it’s

a great way for getting a user’s attention from within a Service or Broadcast Receiver.

• From notification you can invoke activities.• Notification can have extra like sound, vibration, light• RemoteViews (will be explained later) can be used to create custom notification

view

Page 233: Dori waldman android _course

Widget

Page 234: Dori waldman android _course

234

Widget – • widgets are views which display on a home page and can be update

frequently (timer), you can add more than one widget from the same type on the screen (usually with different settings).

• Widget minimum time to update is 1H.

• RemoteView - A class that describes a view hierarchy that can be displayed in another process. The hierarchy is inflated from a layout resource file, and this class provides some basic operations for modifying the content of the inflated hierarchy.

• Widgets use RemoteViews to create there user interface. A RemoteView can be executed by another process with the same permissions as the original application. This way the Widget runs with the permissions of its defining application, meaning you can’t work on the view directly.

Page 235: Dori waldman android _course

235

Create Widget

• Declare widget in manifest

• Adding the AppWidgetProviderInfo Metadata (res/xml/)

• Create widget layouts (View , configure)

• Extends AppWidgetProviderThis class is responsible to paint the RemoteViews according to the

widget instance ID • Create Configuration Activity

Instance parameters needs to be persistence

Code Example

Page 236: Dori waldman android _course

236

What's new

• Since Android 4.2, it is possible to launch Home Screen application widgets on the Lock Screen of an Android device. 

• <appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android" android:widgetCategory="keyguard|home_screen" ... > ... </appwidget-provider>

Page 238: Dori waldman android _course

Custom View

Page 239: Dori waldman android _course

239

Custom View

Extend View/Layout classes and override the appropriate methods (onDraw()…)

Custom/Compound views

Page 240: Dori waldman android _course

Menu

Page 241: Dori waldman android _course

241

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 extended menu.

Page 242: Dori waldman android _course

242

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

Page 243: Dori waldman android _course

243

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>

Page 244: Dori waldman android _course

Web/Hybrid

Page 245: Dori waldman android _course

245

Native vs. Hybrid

Page 246: Dori waldman android _course

246

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

Page 247: Dori waldman android _course

247

Web development Develop regular Html, JS pages without interaction with the device API

Page 248: Dori waldman android _course

248

Spring Mobile (Spring MVC for web mobile)

Page 249: Dori waldman android _course

249

Frameworks (Gwt,PrimeFaces)

http://prezi.com/embed/6ngydrtzj2ln/ (GWT-Mobile / Mgwt)

http://primefaces.org/showcase/mobile/index.jsf ICEmobile 

Page 250: Dori waldman android _course

250

HybridDevelop web pages that can interact with the device native API (via JS)

Page 252: Dori waldman android _course

252

PhoneGap code examplenavigator.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);}

Page 253: Dori waldman android _course

253

Hybrid platforms

Page 254: Dori waldman android _course

254

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"));

Page 255: Dori waldman android _course

Dev/Test tools

Page 256: Dori waldman android _course

256

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 );     } }

@ViewByIdListView bookmarkList;

Backward Compatibility (Fragment):• http://nineoldandroids.com/

• http://actionbarsherlock.com/

• http://developer.android.com/tools/extras/support-library.html

Page 257: Dori waldman android _course

257

Mobile Analytics

Google analyticsDemo

Activity tracking - Button clickException trackingEcommerce Tracking- track shopping cart transactionsCross device analyticsReports : location , carrier, OS version, visit time, unique users …

Page 258: Dori waldman android _course

258

AR

https://developer.vuforia.com/

http://www.junaio.com/

Page 259: Dori waldman android _course

259

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

Test frameworks

Page 260: Dori waldman android _course

260

UiAutomator(outOfApp) vs robotium(inApp):

Page 261: Dori waldman android _course

261

Google Espresso

Testing UI from the main thread ! ! !

http://www.youtube.com/watch?v=T7ugmCuNxDU

Page 262: Dori waldman android _course

262

Hierarchy Viewer / uiAutomatorViewer

uiautomatorviewer : A GUI tool to scan and analyze the UI components of an Android application.

Page 263: Dori waldman android _course

263

IDE – Android Studio

What's New in Android Developer Tools

Page 265: Dori waldman android _course

265

Code Generator Frameworks

Write application in C++ or oriented language and compile to Android app (java)

Page 266: Dori waldman android _course

Cloud

Page 267: Dori waldman android _course

267

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/

Page 268: Dori waldman android _course

268

Android Push (cloud)

Allow to push data from server to deviceshttp://www.youtube.com/watch?v=YoaP6hcDctMhttp://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.htmlhttp://developer.android.com/google/gcm/gs.htmlhttp://www.vogella.de/articles/AndroidCloudToDeviceMessaging/article.html

http://api.shephertz.com/cloudapidocs/guide/0.8.3/android/pushnotification_api.html

Page 269: Dori waldman android _course

Hacking

Page 270: Dori waldman android _course

270

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

Page 271: Dori waldman android _course

Best Practice

Page 273: Dori waldman android _course

Thank u !

Page 274: Dori waldman android _course

274

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.