Introducing Mobile Application Development For Android

Transcription

Introducing Mobile ApplicationDevelopment for AndroidPresented by:Ahmed Misbah

AgendaIntroductionAndroid SDK FeaturesDeveloping an Android ApplicationAndroid MarketAndroid Application Trends

INTRODUCTION

What is Android?Google’s mobile operating systemBased on Linux KernelOffers an SDK and NDKLatest SDK version is 3.0/3.1 (Honeycomb)

Architecture Overview

Linux KernelAndroid uses Linux for its memorymanagement, process management,networking, and other operating systemservices

Native LibrariesShared libraries all written in C or C Compiled for the particular hardwarearchitecture used by the phonePreinstalled by the phone vendorCan be developed using NDK

Native Libraries (cont’d)Surface Manager2D, 3D GraphicsMedia CodecsSQL DatabaseBrowser Engine

Android RuntimeDalvik VMGoogle’s implementation of JavaOptimized for mobile devicesRuns .dex files which are more compact andefficient than standard .class filesCore Java librariesNot those of JSE or JME but have some similarities

Application FrameworkActivity ManagerContent providersResource ManagerLocation ManagerNotification Manager

Application Lifecycle

Building BlocksActivities : User InterfaceIntent: A mechanism for describing a specificactionService: A task that runs in the backgroundwithout user interactionContent providers: is a set of data wrapped upin a custom API to read and write it

Application Structure

ResourcesStored in res folderIncludes all non code information (e.g.localized text and images)Resources compiler compresses and packs allresources in a class named R

Android ManifestEvery application must have anAndroidManifest.xml file in its root directoryManifest presents essential information aboutthe application to the Android system:Java packageComponents of the application (Activities,Services, etc.)Permissions the applicationMinimum level of the AndroidLibraries that the application utilizes

SecurityStored in Android-Manifest.xmlContains following permissions:INTERNETREAD CONTACTSWRITE CONTACTSRECEIVE SMSACCESS COARSE LOCATIONACCESS FINE LOCATIONWRITE EXTERNAL STORAGE

ANDROID SDK FEATURES

Android SDK FeaturesUser InterfaceGraphicsMultimediaData StorageNetworkingLocating and SensingTelephony, Messaging and NotificationI18N and Localization

USER INTERFACE

OverviewDesign MethodsDeclare UI elements in XML (Declarative design)Instantiate UI elements at runtime

Activity ClassActivity class takes care of creating a windowin which UI can be placedThere is a one-to-one relationship between anActivity and a UI screenActivities are made up of subcomponentscalled Views

Activity Lifecycle

ViewsViews are what your users will see andinteract with

Views (cont’d)

Views (cont’d)

Views (cont’d)

ResourcesSome important resource values/styles.xml/res/menu/menu.xml

LayoutsLayouts are defined in /res/layout/main.xmlLayouts are automatically converted to amember in the layout inner class in R class

Layouts (cont’d)Linear Layout: Arranges its children in a singlecolumn or row. This is the most commonlayout you will use

Layouts(cont’d)Relative Layout: Arranges its children inrelation to each other or to the parent. This isoften used in forms

Layouts(cont’d)Table Layout: Arranges its children in rows andcolumns, similar to an HTML table

Tab Activity

ListenersTell Android which object to callback when theuser touches or clicks the viewUse setOnClickListener() method that needs tobe passed an object that implements theOnClickListener Java interfaceSet android:onClick property with the methodname that handles the click action

Applying a ThemeAndroid is packaged with several themes thatyou can reference by name, or you can makeup your own theme by extending existing onesand overriding their default valuesYou can define your own custom theme inres/values/styles.xml

MenusAndroid supports three kinds of menus:Options Menu: the menu you get when you pressthe physical Menu buttonContext Menu: that pops up when you press andhold your finger on the screenSub Menu: a floating list of menu items that theuser opens by pressing a menu

Menus (cont’d)

DialogsA small window that appears in front of thecurrent Activity

Search Activity

GRAPHICS

OverviewAndroid provides a powerful graphics librarythat supports drawing of 2D shapes anddeveloping animations2D Graphics since version 3.0 can also behardware acceleratedFor 3D Graphics, android provides animplementation based on OpenGL ES 1.0 APIs

2D GraphicsAndroid offers a custom 2D graphics library fordrawing and animating shapes and imagesThe android.graphics.drawable andandroid.view.animation packages are whereyou'll find the common classes used fordrawing and animating in two-dimensions

Drawable classA Drawable is a general abstraction for“something that can be drawn.”Subclasses include BitmapDrawable,ShapeDrawable, PictureDrawable, etc.draw method takes a Canvas which handlesdrawing of primitive shapes (Bitmap,rectangle, line, circle, etc.)

AnimationsAndroid support 2 animation frameworks:Property Animation: latest animation frameworkthat allows developers to animate almost anythingView Animation: provides the capability to onlyanimate View objects

Property AnimationAvailable since version 3.0Changes a property's (a field in an object)value over a specified length of time

View AnimationTween Animation: can perform a series ofsimple transformations (position, size, rotation,and transparency) on the contents of a ViewobjectFrame Animation: a traditional animation in thesense that it is created with a sequence ofdifferent images, played in order, like a roll offilm

Live WallpaperIntroduced in version 2.1Like any normal application, can use anyfeature (MapView, Accelerometer, GPS, )Provides an Engine for handling rendering ofWallpaperProvide “settings screen”

MULTIMEDIA

AudioSteps for playing Audio:1. Put sound files in res/raw directory2. Create android.media.MediaPlayer instance3. mediaPlayer.start() stop(), pause(), reset(), prepare(), setLooping(), Useful methods:setVolumeControlStream(AudioManager.STREAM MUSIC)setOnCompletionListener( )

VideoExactly similar to AudioMediaPlayer start(), stop()Just add “Surface” to preview the videoOr simply use p" );video.start();

DATA STORAGE

PreferencesOut of the box preference screenAllows reading and writing applicationresourcesPreference screen components written inresource XMLPreference screen loaded from class whichextends PreferenceActivity

Accessing Internal File SystemAllows access to package private directorycreated at install time(/data/data/packagename)Few helper methods are provided on theContext:deleteFile( )fileList( )openFileInput( )openFileOutput( )

Accessing SD CardRequires WRITE EXTERNAL STORAGEpermissionUses /sdcard/ instead of /data/// Load and start the movievideo.setVideoPath("/sdcard/samplevideo.3gp" );video.start();Use standard java.io to access files

Database accessAndroid utilizes SQLiteA SQLite database is just a single fileAndroid stores the file in the/data/data/packagename/databasesdirectoryUses standard SQL DML and DDL scripts

Database access (cont’d)DB is accessible through a class that extendsSQLiteOpenHelperProvides an object of SQLiteDatabase that exposesmethods like:db.execSQL(String sql)db.insert(String tablename, String nullColumnHack,ContentValues values);db.query (String table, String[] columns, String selection,String[] selectionArgs, String groupBy, String having,String orderBy, String limit)

Database access (cont’d)query methods returns an object of Cursorclass over a result setData binding is possible using ListActivity

BREAK

NETWORKING

Checking Network StatusAvailable using ConnectivityManagerConnectivityManager cMgr .CONNECTIVITY SERVICE);NetworkInfo netInfo tInfo.toString());

SocketsSimilar to JSE socket programming

Bluetooth SocketRequires permissionandroid.permission.BLUETOOTHSetting up Bluetooth:Enabling BluetoothFinding Paired DevicesSearching for DevicesEnabling Discoverability

Bluetooth Socket (cont’d)You can connect as a Server usingBluetoothServerSocketYou can also connect as a client usingBluetoothDevice and BluetoothSocketConnections are managed by BluetoothSocketusing InputStream and OutputStream

Working with HTTPSimilar to JSE using HttpURLConnection andjava.netRobust HTTP with HttpClientHttpClient httpclient new DefaultHttpClient();HttpPost httppost new t NameValuePair pairs new ArrayList NameValuePair (2);pairs.add(new BasicNameValuePair("ID", "VALUE"));httppost.setEntity(new UrlEncodedFormEntity(pairs));HttpResponse webServerAnswer httpclient.execute(httppost);

Working with Web ServicesSOAP Web Services can be invoked using 3rdparty library such as org.ksoap2RESTful Web Service can be implementedusing HttpURLConnection and XML parserand/or JSON library

LOCATING AND SENSING

Locating OverviewSupported Providers:GPSCell TowersWI-FIAccess to location information is protected byAndroid permissions:ACCESS COARSE LOCATIONACCESS FINE LOCATION

Location ManagerProvides access to the system locationservicesRetrieved RVICE)

Location Manager(cont’d)Useful Methods:getAllProviders()getBestProvider(Criteria criteria, booleanenabledOnly)getLastKnownLocation(String provider)requestLocationUpdates(String provider, longminTime, float minDistance, LocationListenerlistener)

Location ListenerUsed for receiving notifications from theLocationManager when the location isupdatedLocation Listener methods:onLocationChanged(Location location)onProviderDisabled(String provider)onProviderEnabled(String provider)onStatusChanged(String provider, int status,Bundle extras)

GeocodingThe process of finding associated geographiccoordinates (often expressed as latitude andlongitude) from other geographic data, suchas street addresses, or zip codes (postal codes)Reverse Geocoding performs the oppositeoperation

Geocoding verse GeocodingAddress

Geocoder ClassA class for handling Geocoding and ReverseGeocodingUseful methods:getFromLocation(double latitude, double longitude, intmaxResults)getFromLocationName(String locationName, intmaxResults, double lowerLeftLatitude, doublelowerLeftLongitude, double upperRightLatitude, ng locationName, intmaxResults)

SensorsAndroid supports many different types ofsensor devices:TYPE ACCELEROMETER: Measures acceleration in the x-, y-, and zaxesTYPE LIGHT: Tells you how bright your surrounding area isTYPE MAGNETIC FIELD: Returns magnetic attraction in the x-, y-, andz-axesTYPE ORIENTATION: Measures the yaw, pitch, and roll of the deviceTYPE PRESSURE: Senses the current atmospheric pressureTYPE PROXIMITY: Provides the distance between the sensor andsome objectTYPE TEMPERATURE: Measures the temperature of the surroundingarea

Sensor ManagerAllows utilizing the device's sensorsAn instance of this class is retrieved bycalling Context.getSystemService(Context.SENSOR SERVICE)Specific sensors are retrieved usinggetDefaultSensor(Sensor.TYPE ACCELEROMETER)

SensorEventListenerReceives notifications from theSensorManager when sensor values areupdatedCallback Methods:onAccuracyChanged(Sensor sensor, intaccuracy)onSensorChanged(SensorEvent event)

TELEPHONY, MESSAGING ANDNOTIFICATIONS

Telephony ManagerProvides access to information about thetelephony services on the deviceRequires READ PHONE STATE permissionGet an instance of this class by callingContext.getSystemService(Context.TELEPHONY SERVICE)

Telephony Manager(cont’d)PhoneStateListener A listener class formonitoring changes in specific telephonystates on the device, including service state,signal strength, message waiting indicator(voicemail), and others

SMS Messages SupportAndroid API supports developing applicationsthat can send and receive SMS messagesSmsManager Manages SMS operations suchas sending data, text, and PDU SMS messagesRequires SEND SMS permission

NotificationsA Notification is a persistentmessage that not only showsup in the status bar but staysin a notification area until theuser deletes itManaged by Notification andNotificationManager Classes

I18N AND LOCALIZATION

LocalizationAll resources in Android can be configured to supportlocalizationExample:Default (English): res/values/strings.xmlArabic: res/values-ar/strings.xmlFrench: res/values-fr/strings.xmlUse Android context to change localeLocale locale context.getResources().getConfiguration().locale

DEVELOPING AN ANDROID APP

SDKContains Dalvik VM, Java libraries andEmulator

IDEAn Android plugin, called AndroidDevelopment Tools (ADT) (https://dlssl.google.com/android/eclipse/), is availablefor Eclipse IDEMotoDev is an Eclipse based IDE withtremendous features for AndroidDevelopment

Create an AVD

Create new project

Development Checklist

Debugging

Package and deploySign application using Eclipse Export WizardChoose a strong password to sign yourapplicationApplication is exported to an APK file

Publish to marketPublishing checklist:1. Test your application extensively on an actualdevice2. Consider adding an End User License Agreementin your application3. Consider adding licensing support4. Specify an icon and label in the application'smanifest5. Turn off logging and debugging and clean updata/files

Publish to market (cont’d)6. Version your application7. Obtain a suitable cryptographic key8. Register for a Maps API Key, if your application isusing MapView elements9. Sign your application10. Obfuscate your code using ProGuardFollow MotoDev publishing steps

Support and ResourcesAndroid )Offers SDK downloads, Reference (JAVADOCs),Resources and Dev Guide

ANDROID MARKET

OverviewAndroid’s application repositorySimilar to Apple’s App Store and Nokia’s OviStoreBy August 2010, there were over 80,000applications available for download, with over1 billion application downloads

Overview (cont’d)

Overview (cont’d)

Publishing on Android Market1. Create a developer profile using a Googleaccount2. Pay a registration fee of 25 3. For paid applications, Google receives a 30%transaction fee4. Google handles version updates

ANDROID APPLICATION TRENDS

What are analysts saying?“Android Is Destroying Everyone, EspeciallyRIM -- iPhone Dead In Water” - BusinessInsider“Android market share to near 50 percent” Gartner“Android's Market Share Soars Ahead OfApple iPhone's” - The Huffington Post

Market ShareData collected on Q4 2010

Market Share (cont’d)

Usage ShareData collected on May 2011

Available Applications

Paid vs. Free

Category Analysis

Category Analysis (cont’d)

Key factors for 2010Entertainment category will remain mostpopularFree applications will continue to dominateThe rise of books and reference categories

Future of Android AppsLocalized contentMore mature business applicationsApplications for Tablet devicesApplications utilizing location and mapsSocial Network aggregatorsSatallite Systems (SSTL)Software Development process for mobileapplications

Gartner Top 10 Mobile Applicationsfor 2012Mobile Money TransferLocation-Based ServicesMobile SearchMobile BrowsingMobile Health MonitoringMobile PaymentNear Field Communication ServicesMobile AdvertisingMobile Instant MessagingMobile Music

Thank you

View Animation Tween Animation: can perform a series of simple transformations (position, size, rotation, and transparency) on the contents of a View object Frame Animation: a traditional animation in the sense that it is created with a sequence