Vous êtes sur la page 1sur 124

Mobile Application Development

Agenda
Introduction Mobile Devices Profile Mobile Software Option For Development

Introduction

Mobile application development is the process by which application software is developed for small lowpower handheld devices such as personal digital assistants, enterprise digital assistants or mobile phones. These applications are either pre-installed on phones during manufacture, or downloaded by customers from various mobile software distribution platforms.

Mobile Devices Profile


A profile defines a set of APIs and capabilities typically supported on a particular class of device. The mobile device profile defines a set of capabilities for applications that are installed on mobile devices such as cell phones and tablets. These applications install and run on supported mobile platforms, including Android, Blackberry Tablet OS, and iOS.

Mobile Applications
One of the primary considerations in creating mobile applications for your business is the type of the application. This requires an understanding of the different options available in building mobile applications. Mobile applications can be built as: Native applications (or) Web/browser applications.

Native applications
A native mobile application is a piece of software for Smartphones and tablets.
These applications are built specifically for each mobile platform and are installed on the device. The application is specifically designed to run on the devices operating system and machine firmware. Native applications can be built as: Device specific applications These applications are developed using proprietary or device specific languages/tools like Objective C, Android SDK, Blackberry SDK etc.

Multiplatform applications - These applications can be deployed on different devices using the same codebase. Frameworks like Rhodes, Phone Gap, Mother App etc. are used in building these applications.

Web applications
These applications are designed for use on specific Smartphones or Tablets and are accessed through the devices web browser (Safari, Internet Explorer, etc). Each time an application is run on the device, all or some parts of the software is downloaded from the Web.

Since mobile web applications are accessed through the browser without requiring installation on each device, they are platform independent.

The key difference between the above mentioned application types is that

Native applications are installed directly on each device, whereas


Web applications are served from a central location (Web Server) and accessed through a web browser

Advantages of Native Applications

Performance- Web applications largely depend upon the browsers performance. The browser resides between the application and the OS. If the browser is not functioning well, the performance of the web application will also be affected and will go slow

But in the case of Native Applications, all the screens load instantly. If the screen depends upon dynamic data from the server, the complete screen comes up first and the data is loaded as-synchronously i.e. in background. The advantage here is that the users will not have to wait for the UI to load. Limited Device Feature Access - Web applications run on browsers and hence may miss out on many very useful features such as access to the Photo library, the Address book, the Camera, the Accelerometer, the Music Library, Voice recording, device specific data etc. Alerts - Native Applications can accommodate alerts using which the user can be notified for future tasks. Alerts cannot be accommodated in Web Applications.

Data Management - Web Applications support offline SQL databases and the records are stored locally. This will reduce performance when compared to native applications as the browser would communicate with the local database and with multiple tabs open, the speed of the application would go down. Also, if the browser data is cleared, all local data would be deleted, thus affecting the performance of the web application.

Option For Development


Android, iOS, BlackBerry, HP webOS, Symbian OS, and Windows Mobile are various execution environment that provide support for applications. Android is one of the best mobile OS there is, it's fast, flexible has great support for customisation, a pretty decent app store and it's becoming very popular which means more support from developers and more effort put into making better Android phones

The Big Picture What Is Android?

Android is a software bunch comprising not only operating system but also middleware and key applications. Android Inc was founded in Palo Alto of California, U.S. by Andy Rubin, Rich miner, Nick sears and Chris White in 2003. Later Android Inc. was acquired by Google in 2005. After original release there have been number of updates in the original version of Android.

Android is a powerful Operating System supporting a large number of applications in smart phones.

Hardwares that support Android are mainly based on ARM architecture platform.

Some of the current features and specifications of android are:

Android applications are written in java programming language.

Android is available as open source for developers to develop applications which can be further used for selling in android market.
Android relies on Linux version 2.6 for core system services such as security, memory management, process management, network stack, and driver

Development Environment

The Android SDK Building Android Application In Eclipse

The Android Emulator


Debugging

The Android SDK

A software development kit that enables developers to create applications for the Android platform.
The Android SDK includes sample projects with source code, development tools, an emulator, and required libraries to build Android applications.

Applications are written using the Java programming language and run on Dalvik, a custom virtual machine designed for embedded use which runs on top of a Linux kernel. Virtual Machine is a self-contained operating environment that behaves as if it is a separate computer

Installing The SDK


The system and software requirements for developing Android applications using the Android SDK. Supported Operating Systems Windows XP (32-bit), Vista (32- or 64-bit), or Windows 7 (32- or 64-bit) Mac OS X 10.5.8 or later (x86 only) Linux (tested on Ubuntu Linux, Lucid Lynx) GNU C Library (glibc) 2.7 or later is required. On Ubuntu Linux, version 8.04 or later is required.

Step1:
You need to install jdk and suitable version of eclipse. The "Eclipse Classic" version is recommended. Otherwise, a Java or RCP version of Eclipse is recommended.

Step 2:
Download the sdk starter package.

Step 3: Installing the ADT Plugin for Eclipse


Android offers a custom plugin for the Eclipse IDE, called Android Development Tools (ADT),

that is designed to give you a powerful, integrated environment in which to build Android applications. It extends the capabilites of Eclipse to let you quickly set up new Android projects, create an application UI, debug your applications using the Android SDK tools, and even export signed (or unsigned) APKs in order to distribute your application.
1.Start Eclipse, then select Help > Install New Software....

Click Add, in the top-right corner.


2.In the Add Repository dialog that appears, enter "ADT Plugin" for the Name and the following URL for the Location:

https://dl-ssl.google.com/android/eclipse/ 4.Click OK 5. In the Available Software dialog, select the checkbox next to Developer Tools and click Next. 6.In the next window, you'll see a list of the tools to be downloaded. Click Next. 7.Read and accept the license agreements, then click Finish. 8.When the installation completes, restart Eclipse.

Step 4: Adding Platform and other components


You can launch the Android SDK and AVD Manager in one of the following ways: From within Eclipse, select Window > Android SDK and AVD Manager.

On Windows, double-click the SDK Manager.exe file at the root of the Android SDK directory.
On Mac or Linux, open a terminal and navigate to the tools/ directory in the Android SDK, then execute:android

Building Android Application In Eclipse


It's particularly easy if you're using Eclipse as your IDE, because android provides a great plugin that handles project creation and management to greatly speed up your development cycles. Before you start, you should already have the SDK installed, and should have installed the ADT plugin as well. To build an application we also require to install a platform and create an AVD(Android Virtual Device).

Install a Platform
To install a platform in Eclipse: In the Android SDK and AVD Manager, choose Available Packages in the left panel.

In the right panel, expand the Android Repository list to display the components available for installation.
Select at least one platform to install, and click Install Selected. If you aren't sure which platform to install, use the latest version.

Create an AVD
An AVD defines the system image and device settings used by the emulator. To create an AVD:

In Eclipse, select Window > Android SDK and AVD Manager.


Select Virtual Devices in the left panel. Click New.... The Create New AVD dialog appears.

Type the name of the AVD, such as "my_avd". Choose a target. The target is the platform (that is, the version of the Android SDK, such as 2.3.3) you want to run on the emulator. For this tutorial, choose the latest platform that you have installed and ignore the rest of the fields.

Click Create AVD.

Create a New Android Project


In Eclipse, select File > New > Project.... Select "Android Project" and click Next.

Fill in the project details with the following values: Project name: HelloAndroid Build Target: Select a platform version that is equal to or lower than the target you chose for your AVD.

Application name: Hello, Android


Package name: com.example.helloandroid (or your own private namespace) Create Activity: HelloAndroid Click Finish.

Your Android project is now ready. It should be visible in the Package Explorer on the left. Open the HelloAndroid.java file, located inside HelloAndroid > src > com.example.helloandroid). It should look like this: package com.example.helloandroid; import android.app.Activity; import android.os.Bundle; public class HelloAndroid extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState); // setContentView(R.layout.main); TextView tv = new TextView(this); tv.setText("Hello World"); setContentView(tv); } }

Run the Application


The Eclipse plugin makes it easy to run your applications:
Select Run > Run. Select "Android Application".

The Android Emulator


The emulator lets you prototype, develop, and test Android applications without using a physical device. The Android emulator mimics all of the hardware and software features of a typical mobile device, except that it cannot place actual phone calls. It provides a variety of navigation and control keys, which you can "press" using your mouse or keyboard to generate events for your application. To let you model and test your application more easily, the emulator utilizes Android Virtual Device (AVD) configurations.

AVDs let you define certain hardware aspects of your emulated phone and allow you to create many configurations to test many Android platforms and hardware permutations. Once your application is running on the emulator, it can use the services of the Android platform to invoke other applications, access the network, play audio and video, store and retrieve data, notify the user, and render graphical transitions and themes.

The Android emulator is a QEMU-based application that provides a virtual ARM mobile device on which you can run your Android applications. It runs a full Android system stack, down to the kernel level, that includes a set of preinstalled applications (such as the dialer) that you can access from your applications.

You can choose what version of the Android system you want to run in the emulator by configuring AVDs, and you can also customize the mobile device skin and key mappings. When launching the emulator and at runtime, you can use a variety of commands and options to control its behaviors.

The Android system image distributed in the SDK contains ARM machine code for the Android Linux kernel, the native libraries, the Dalvik VM, and the various Android package files (such as for for the Android framework and preinstalled applications).
The emulator's QEMU layers provide dynamic binary translation of the ARM machine code to the OS and processor architecture of your development machine.

Emulator Limitations
No support for placing or receiving actual phone calls. You can simulate phone calls (placed and received) through the emulator console, however. No support for USB connections No support for camera/video capture (input). No support for device-attached headphones No support for determining connected state No support for determining battery charge level and AC charging state

No support for determining SD card insert/eject


No support for Bluetooth

Debugging
Debugging is a methodical process of finding and reducing the number of bugs, or defects, in a computer program or a piece of electronic hardware, thus making it behave as expected. The Android SDK provides most of the tools that we need to debug your applications.
We need a JDWP-compliant debugger if we want to be able to do things such as step through code, view variable values, and pause execution of an application. In Eclipse, a JDWP-compliant debugger is already included and there is no setup required.

The main components that comprise a typical Android debugging environment are
:

Android Debug Bridge (adb) Dalvik Debug Monitor Server Device or Android Virtual Device

Android Debug Bridge (adb)


adb acts as a middleman between a device and your development system. It provides various device management capabilities, including moving and syncing files to the emulator, running a UNIX shell on the device or emulator, and providing a general means to communicate with connected emulators and devices. Android Debug Bridge (adb) is a versatile command line tool that lets you communicate with an emulator instance or connected Android-powered device. It is a client-server program that includes three components:

1.A client, which runs on your development machine. You can invoke a client from a shell by issuing an adb command. Other Android tools such as the ADT plugin and DDMS also create adb clients. 2.A server, which runs as a background process on your development machine. The server manages communication between the client and the adb daemon running on an emulator or device. 3.A daemon, which runs as a background process on each emulator or device instance. You can find the adb tool in <sdk>/platform-tools/.

Dalvik Debug Monitor Server


DDMS is a graphical program that communicates with your devices through adb. DDMS can capture screenshots, gather thread and stack information, spoof incoming calls and SMS messages, and has many other feature. Running DDMS DDMS is integrated into Eclipse and is also shipped in the tools/ directory of the SDK. DDMS works with both the emulator and a connected device. From Eclipse: Click Window > Open Perspective > Other... > DDMS.

Device or Android Virtual Device


Your application must run in a device or in an AVD so that it can be debugged. An adb device daemon runs on the device or emulator and provides a means for theadb host daemon to communicate with the device or emulator.

User interface
The user interface, in the design field of human machine interaction, is the space where interaction between humans and machines occurs. The goal of interaction between a human and a machine at the user interface is effective operation and control of the machine, and feedback from the machine which aids the operator in making operational decisions. A user interface is the system by which people (users) interact with a machine. The user interface includes hardware (physical) and software (logical) components.

User interfaces exist for various systems, and provide a means of:
Input, allowing the users to manipulate a system Output, allowing the system to indicate the effects of the users' manipulation In an Android application, the user interface is built using View and ViewGroup objects. There are many types of views and view groups, each of which is a descendant of the View class.

View objects are the basic units of user interface expression on the Android platform. The View class serves as the base for subclasses called "widgets," which offer fully implemented UI objects, like text fields and buttons.

A View object is a data structure whose properties store the layout parameters and content for a specific rectangular area of the screen. As an object in the user interface, a View is also a point of interaction for the user and the receiver of the interaction events. On the Android platform, you define an Activity's UI using a hierarchy of View and ViewGroup nodes

Agenda
Activity Life cycle Creating the Activity An overview of user interfaces Using XML layouts Selection Widgets The Web view & the Web Kit Browser Dialogue Boxes: Alert Dialogue & Toast Using Resources

Activity Life cycle


An activity is a single, focused thing that the user can do.

Almost all activities interact with the user, so the Activity class takes care of creating a window for you in which you can place your UI with setContentView(View) There are two methods almost all subclasses of Activity will implement:
1.onCreate(Bundle) is where you initialize your activity. Most importantly, here you will usually call setContentView(int) with a layout resource defining your UI, and using findViewById(int) to retrieve the widgets in that UI that you need to interact with programmatically.

2. onPause( ) is where you deal with the user leaving your activity. Most importantly, any changes made by the user should at this point be committed (usually to the ContentProvider holding the data). All activity classes must have a corresponding <activity> declaration in their package's AndroidManifest.xml. The Activity class is an important part of an application's overall lifecycle, and the way activities are launched and put together is a fundamental part of the platform's application model.

Activities in the system are managed as an activity stack. When a new activity is started, it is placed on the top of the stack and becomes the running activity -- the previous activity always remains below it in the stack, and will not come to the foreground again until the new activity exits.
An activity has essentially four states:

1. If an activity in the foreground of the screen (at the top of the stack), it is active or running.
2. If an activity has lost focus but is still visible (that is, a new non-full-sized or transparent activity has focus on top of your activity), it is paused. A paused activity is completely alive (it maintains all state and member information and remains attached to the window manager), but can be killed by the system

in extreme low memory situations.


3.If an activity is completely obscured by another activity, it is stopped. It still retains all state and member information, however, it is no longer visible to the user so its window is hidden and it will often be killed by the system when memory is needed elsewhere.

4.If an activity is paused or stopped, the system can drop the activity from memory by either asking it to finish, or simply killing its process. When it is displayed again to the user, it must be completely restarted and restored to its previous state.

There are three key loops in monitoring within your activity:


1.The entire lifetime of an activity happens between the first call to onCreate(Bundle) through to a single final call to onDestroy(). An activity will do all setup of "global" state in onCreate(), and release all remaining resources in onDestroy(). For example, if it has a thread running in the background to download data from the network, it may create that thread in onCreate() and then stop the thread in onDestroy(). 2.The visible lifetime of an activity happens between a call to onStart() until a corresponding call to onStop(). During this time the user can see the activity on-screen, though it may not be in the foreground and interacting with the user. Between these two methods you can maintain resources that are needed to show the activity to the user.

For example, you can register a BroadcastReceiver in onStart() to monitor for changes that impact your UI, and unregister it in onStop() when the user an no longer see what you are displaying. The onStart() and onStop() methods can be called multiple times, as the activity becomes visible and hidden to the user.
3.The foreground lifetime of an activity happens between a call to onResume() until a corresponding call to onPause(). During this time the activity is in front of all other activities and interacting with the user. An activity can frequently go between the resumed and paused states -- for example when the device goes to sleep, when an activity result is delivered, when a new intent is delivered -- so the code in these methods should be fairly lightweight.

The entire lifecycle of an activity is defined by the following Activity methods


You should always call up to your superclass when implementing these methods. public class Activity extends ApplicationContext { protected void onCreate(Bundle savedInstanceState); protected void onStart(); protected void onRestart(); protected void onResume();

protected void onPause(); protected void onStop(); protected void onDestroy(); }

Creating the Activity


An application usually consists of multiple activities that are loosely bound to each other. Typically, one activity in an application is specified as the "main" activity, which is presented to the user when launching the application for the first time. Each activity can then start another activity in order to perform different actions. Each time a new activity starts, the previous activity is stopped, but the system preserves the activity in a stack (the "back stack").

To create an activity, you must create a subclass of Activity(or an existing subclass of it).
In your subclass, you need to implement callback methods that the system calls when the activity transitions between various states of its lifecycle, such as when the activity is being created, stopped, resumed, or destroyed.

The two most important callback methods are:


onCreate( );

onPause( );

Declaring the activity in the manifest


You must declare your activity in the manifest file in order for it to be accessible to the system. To declare your activity, open your manifest file and add an <activity> element as a child of the <application> element. For example: <manifest ... > <application ... > <activity android:name=".ExampleActivity" />

...
</application ... > ... </manifest > There are several other attributes that you can include in this element, to define properties such as the label for the activity, an icon for the activity, or a theme to style the activity's UI. An <activity> element can also specify various intent filters using the <intent-filter> elementin order to declare how other application components may activate it.

When you create a new application using the Android SDK tools, the stub activity that's created for you automatically includes an intent filter that declares the activity responds to the "main" action and should be placed in the "launcher" category.
The intent filter looks like this: <activity android:name=".ExampleActivity" android:icon="@drawable/app_icon"> <intent-filter>

<action android:name="android.intent.action.MAIN" />


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

</intent-filter>
</activity> The <action> element specifies that this is the "main" entry point to the application. The <category> element specifies that this activity should be listed in the system's application launcher (to allow users to launch this activity).

An overview of user interfaces


In an Android application, the user interface is built using View and ViewGroup objects. There are many types of views and view groups, each of which is a descendant of the View class.

View objects are the basic units of user interface expression on the Android platform.
The View class serves as the base for subclasses called "widgets," which offer fully implemented UI objects, like text fields and buttons.

The ViewGroup class serves as the base for subclasses called "layouts," which offer different kinds of layout architecture, like linear, tabular and relative. A View object is a data structure whose properties store the layout parameters and content for a specific rectangular area of the screen. A View object handles its own measurement, layout, drawing, focus change, scrolling, and key/gesture interactions for the rectangular area of the screen in which it resides As an object in the user interface, a View is also a point of interaction for the user and the receiver of the interaction events.

Using XML layouts


The most common way to define your layout and express the view hierarchy is with an XML layout file. Each element in XML is either a View or ViewGroup object (or descendant thereof). The name of an XML element is respective to the Java class that it represents.

So a <TextView> element creates a TextView in your UI, and a <LinearLayout> element creates a LinearLayout view group.

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.co m/apk/res/android"


android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello, I am a TextView" />

Load the XML Resource


When you compile your application, each XML layout file is compiled into a view resource. You should load the layout resource from your application code, in your Activity.onCreate() callback implementation.

Do so by calling setContentView(), passing it the reference to your layout resource in the form of: R.layout.layout_file_name
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_layout);}

Selection Widget
A widget is a View object that serves as an interface for interaction with the user. Android provides a set of fully implemented widgets, like buttons, checkboxes, and text-entry fields, so you can quickly build your UI. Some widgets provided by Android are more complex, like a date picker, a clock, and zoom controls. But you're not limited to the kinds of widgets provided by the Android platform. If you'd like to do something more customized and create your own actionable elements, you can, by defining your own View object or by extending and combining existing widgets

The widget in android is provided by android.widget package.


Here is a list of files needed to create to implement a custom widget: Java implementation file - This is the file that implements the behavior of the widget. If you can instantiate the object from layout XML, you will also have to code a constructor that retrieves all the attribute values from the layout XML file. XML definition file - An XML file in res/values/ that defines the XML element used to instantiate your widget, and the attributes that it supports. Other applications will use this element and attributes in their in another in their layout XML

Layout XML[optional]- An optional XML file inside res/layout/ that describes the layout of your widget. You could also do this in code in your Java file.

The Web view & the Web Kit Browser


WebKit is a layout engines designed to allow web browsers to render webpages. A layout engine is a software component that takes marked up content (such as HTML, XML, image files, etc.) A View that displays web pages. View class is the basis upon which you can roll your own web browser or simply display some online content within your Activity.

It uses the WebKit rendering engine to display web pages and includes methods to navigate forward and backward through a history, zoom in and out, perform text searches and more. To enable the built-in zoom, set WebSettings.setBuiltInZoomControls(boolean)
In order for your Activity to access the Internet and load web pages in a WebView, you must add the INTERNET permissions to your Android Manifest file: <uses-permission android:name="android.permission.INTERNET" />

Embed an Android WebView in your application


Step1: Presentation

Step 2: Setting up the web view widget


declare the WebView widget as a child of the LinearLayout element, making sure to specify an ID so you can access the widget later. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/and roid"

android:orientation="vertical"
android:layout_width="fill_parent"

android:layout_height="fill_parent" >

<WebView android:id="@+id/web_engine"
android:layout_width="fill_parent" android:layout_height="fill_parent" /> </LinearLayout>

Step 3: Requesting Internet Permission from the Android Manifest


We have to make sure to request permission to access the Internet in AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>


<manifest xmlns:android="http://schemas.android.com/ap k/res/android" package="com.webkitdemo"> <usespermission android:name="android.permission.INTERNET " /> <application android:icon="@drawable/icon" android:la bel="WebKitDemo"> <activity android:name=".WebKitDemo">

<intent-filter>
<action android:name="android.intent.action.MAIN"/> <category android:name="android.intent.category.LAUNCH ER"/> </intent-filter>

</activity>
</application>

</manifest>

Step 4: Load a Web Page


Open up your main activity and add the following code into the onCreate() method: WebView engine = (WebView) findViewById(R.id.web_engine); engine.loadUrl("http://www.google.com");

Dialogue Boxes: Alert Dialogue & Toast


A dialog is usually a small window that appears in front of the current Activity. The underlying Activity loses focus and the dialog accepts all user interaction. Dialogs are normally used for notifications that should interupt the user and to perform short tasks that directly relate to the application in progress (such as a progress bar or a login prompt).

The typical alert dialog provides information in a separate box to the user, after which the user can only respond in one way: by closing it. Closing an alert dialog will provide access to the original window, which is not available while the alert dialog is presented.
A Toast is a view containing quick little message for the user.

When the toast view is shown to the user, appears as a floating view over the application.
Toast will never receive focus

Creating an AlertDialog
An Alert Dialog is an extension of the Dialog class.

You should use it for dialogs that use any of the following features:
1.A title 2.A text message 3.One or two buttons 4.A list of selectable items (with optional checkboxes or radio buttons)

To create an AlertDialog, use the AlertDialog.Builder subclass.


Get a Builder with AlertDialog.Builder(Context) and then use the class's public methods to define all of the AlertDialog properties. After you're done with the Builder, retrieve the AlertDialog object with create(). To create an AlertDialog with side-by-side buttons

AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("Are you sure you want to exit?") .setCancelable(false) .setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { MyActivity.this.finish(); } })

The screenshot below shows an example toast notification

A toast can be created and displayed from an Activity or Service.

Instantiate a Toast object with one of the makeText() methods This method takes three parameters: the application Context, the text message, and the duration for the toast. You can display the toast notification with show() Context context = getApplicationContext(); CharSequence text = "Hello toast!"; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration); toast.show();
.

.setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } });

Using Resources
Resources in Android are files stored under the res directory of your project. Resources can be physical files (Audio, video, images, text, etc) or xml files that declare some values to use in your application
.

Why use Resources: The resources are bound to the application in a way that you can change them without needing to change the source code or recompile the application.

The Android Generates an ID for each resource file so you can access them directly and easily. All the resources IDs are added to the R.Java file.

When you use XML resource files, Android pareses these files automatically so you can reference values defined in them directly with no extra effort. Using resources is very useful in Localization and Internationalization of the application in case you develop multilingual applications. This includes not just the labels but it can include alignment, directions images or any kind of files.

Types of resources:
Strings, colors, arrays, dimensions. Defined in res/values/ directory. Using them is very useful in Localization and Internationalization.

Images put in res/drawable directory. You can put all the images or icons you need in your application. XML, defined in res/xml/ directory for xml files containing your custom data. Layout resources, defined in res/layout/ for declaring the views that construct the user interface of the activities.

Intents and Service


Three of the core components of an application activities, services, and broadcast receivers are activated through messages, called intents. A Service is an application component that can perform long-running operations in the background and does not provide a user interface. Another application component can start a service and it will continue to run in the background even if the user switches to another application.

Agenda
Working with Intent Classes Building a service Communication

Working with Intent Classes


There are separate mechanisms for delivering intents to each type of component: An Intent object is passed to Context.startActivity() or Activity.startActivityForResult() to launch an activity or get an existing activity to do something new. An Intent object is passed to Context.startService() to initiate a service or deliver new instructions to an ongoing service. Similarly, an intent can be passed to Context.bindService() to establish a connection between the calling component and a target service. It can optionally initiate the service if it's not already running.

Intent objects passed to any of the broadcast methods (such as Context.sendBroadcast(), Context.sendOrderedBroadcast(), or Context.sendStickyBroadcast()) are delivered to all interested broadcast receivers.
An Intent object is a bundle of information. It contains information of interest to the component that receives the intent (such as the action to be taken and the data to act on) plus information of interest to the Android system (such as the category of component that should handle the intent and instructions on how to launch a target activity).

Building a service
A Service is an application component representing either an application's desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use.

Each service class must have a corresponding <service> declaration in its package's AndroidManifest.xml. Services can be started with Context.startService() and Context.bindService(). Services can be started with Context.startService() and Context.bindService().

Note that services, like other application objects, run in the main thread of their hosting process.
This means that, if your service is going to do any CPU intensive (such as MP3 playback) or blocking (such as networking) operations, it should spawn its own thread in which to do that work.

The IntentService class is available as a standard implementation of Service that has its own thread where it schedules its work to be done.

Communication
Here is a sample activity that will invoke a service
,

/**
* this is the main activity - File Scanner

* @author sschauhan
*/

public class FileScanner extends Activity


{

@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //just pass the reference to the service FileScannerService.setMainActivity(this); //creating an intent for the service

final Intent fileScannerService = new Intent(this, FileScannerService.class);


//start button Button btnStart = (Button) findViewById(R.id.btn_start);

//start button on click btnStart.setOnClickListener(new View.OnClickListener() { public void onClick(View view)

{
//start the service

startService(fileScannerService);
//remove or hide the app

Finish();
}});

//stop button
Button btnStop = (Button) findViewById(R.id.btn_stop); //on click of stop button btnStop.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { //stop the service stopService(fileScannerService); //remove or hide the app

finish(); } });}

public class FileScannerService extends Service


{ public static FileScanner MAIN_ACTIVITY; private Timer timer=new Timer(); private static long UPDATE_INTERVAL = 1*60*1000; //default private static long DELAY_INTERVAL = 0;

// hooks main activity here


public static void setMainActivity(FileScanner activity) { MAIN_ACTIVITY = activity; }}

@Override public void onCreate(){ super.onCreate(); startService();

if (MAIN_ACTIVITY != null) Log.d(getClass().getSimpleName(), "FileScannerService started"); }

Networking and Web Services


In the world of computers, networking is the practice of linking two or more computing devices together for the purpose of sharing data. Networks are built with a mix of computer hardware and computer software. A Web service is a method of communication between two electronic devices over a network.

The W3C defines a "Web service" as "a software system designed to support interoperable machine-to-machine interaction over a network.

Working with HTTP


Web Services in Android is used by the help of HttpClient.

There is a simple way to make requests to web services and APIs (and plain html pages if you want).
We can also post values on server using HttpClient. The class uses the org.apache.http library which is included in Android.

public void postData() { // Create a new HttpClient and Post Header HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php" ); try { // Add your data List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("id", "12345"));

// Execute HTTP Post Request HttpResponse response = httpclient.execute(httppost); } catch (ClientProtocolException e) { // TODO Auto-generated catch block } catch (IOException e) { // TODO Auto-generated catch block } }

Make request using HttpClient: AsyncHttpClient client = new AsyncHttpClient(); client.get("http://www.google.com", new AsyncHttpResponseHandler() { @Override public void onSuccess(String response) { System.out.println(response); } });

Storing and Retrieving Data


The Storing and Retreiving of data in android can be done in two ways either by using SharedPreferences to store values on the disc or by using ContentResolver to save values in database. The SharedPreferences class provides a general framework that allows you to save and retrieve persistent key-value pairs of primitive data types.

You can use SharedPreferences to save any primitive data: booleans, floats, ints, longs, and strings.

This data will persist across user sessions (even if your application is killed).

To get a SharedPreferences object for your application, use one of two methods:
getSharedPreferences() - Use this if you need multiple preferences files identified by name, which you specify with the first parameter. getPreferences() - Use this if you need only one preferences file for your Activity. Because this will be the only preferences file for your Activity, you don't supply a name.

To write values: 1.Call edit() to get a SharedPreferences.Editor. 2.Add values with methods such as putBoolean() and putString().

3.Commit the new values with commit().


// We need an Editor object to make preference changes.

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);


SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("silentMode", mSilentMode);

// Commit the edits! editor.commit(); // Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); boolean silent = settings.getBoolean("silentMode", false);

setSilent(silent);

Content Providers
Content providers store and retrieve data and make it accessible to all applications. They're the only way to share data across applications; there's no common storage area that all Android packages can access. Android ships with a number of content providers for common data types (audio, video, images, personal contact information, and so on). You can see some of them listed in the android.provider package.

You can then use the ContentResolver's methods to interact with whatever content providers you're interested in.

When a query is initiated, the Android system identifies the content provider that's the target of the query and makes sure that it is up and running. The system instantiates all ContentProvider objects;
The interaction between processes is handled by the ContentResolver and ContentProvider classes.

// Make the query. Cursor managedCursor = managedQuery(contacts, projection, // Which columns to return null, // Which rows to return (all rows) null, // Selection arguments (none) // Put the results in ascending order by name People.NAME + " ASC"); // retreiving values using cursor name = cur.getString(nameColumn); // Add Abraham Lincoln to contacts and make him a favorite. values.put(People.NAME, "Abraham Lincoln");

Multimedia
The Android multimedia framework includes support for capturing and playing audio, video and images in a variety of common media types, so that you can easily integrate them into your applications.

You can play audio or video from media files stored in your application's resources, from standalone files in the file system, or from a data stream arriving over a network connection, all using the MediaPlayer or JetPlayer APIs.
You can also record audio, video and take pictures using the MediaRecorder and Camera APIs if supported by the device hardware.

Playing audio in Android


There are more than one way to play audio and video content in Android, but the easiest way to play media content is by using MediaPlayer. MediaPlayer class can play all the supported audio content. It can play audio from application resource, file or from a streaming source. Playback of audio or video content is managed as a state machine Following are the steps to play an audio content from an application resource: 1. Create a media player using MediaPlayer.create(context,resourceid)

2. Call MediaPlayer.prepare() method and 3. Call MediaPlayer.start() method


.

MediaPlayer player = MediaPlayer(this,R.raw.soundfile); player.prepare(); player.start();

player.stop(); player.reset();

player.release();
player = null;

Thankyou

Vous aimerez peut-être aussi