ANDROID APP WORKSHOP
ANDROID MOBILE APPLICATION DEVELOPMENT
By
TARGET SOFT SYSTEMSCHENNAI
Starting with simple regular handsets which were used just for making phone calls, mobiles have changed our lives and have become part of it. Now they are not used just for making calls but they have innumerable uses and can be used as a Camera , Music player, Tablet PC, T.V. , Web browser etc . And with the new technologies, new software and operating systems are required.
World is contracting with the growth of mobile phone technology. As the number of users is increasing day by day, facilities are also increasing.
NEED FOR MOBILITY SOLUTIONS
NEED FOR MOBILITY SOLUTIONS
• We are in Mobile Internet Computing.• Technology Reach is in Billions not in Millions. • Customers/Partners/Employees are more on mobility.
ANDROID DOMINATION IN SMARTPHONE OS MARKET
REFRESHMENT OF OOPS » What is OOPS ?
» Object
» Class
» Abstraction
» Encapsulation
» Inheritance
» Polymorphism(Run Time & Compile Time)
Object Oriented Programming System
Object Oriented Programming is a methodology to design a program using Classes and Objects.
It simplifies the software development and maintenance by providing some concepts:
> Object > Class> Inheritance> Polymorphism> Abstraction> Encapsulation
OBJECTA runtime entity that has state and behavior is known as Object.
Object= data + method ,Object is an instance of a class.
An object has these characteristics:
State: represents the data of an Object.Behavior: represents the behavior of an Object.Identity: object is typically implemented via a unique ID.
Real time Example:Pen is an object. Its name is Reynolds, color is White etc,.Known as it state.It is used to write, so Writing is its behavior.
CLASS
A Class is a group of objects that have common property. (or)
Collection of Objects. It is a Template or Blue Print from which objects are created.
Syntax to declare a Class:
Class <class name> { data member; method; }
Example for Class and Object: Class student { String name = “Target Soft Systems ”; int phoneno = “9382383393”; public static void main( string[] args) { Student s1 = new student(); // object System.out.println(“Name is:” +s1.name); System.out.println(“Phone No:” +s1.phoneno); }
} Output: Name is: Target Soft Systems Phone No: 9382383393
ABSTRACTIONAbstraction is a process of hiding the implementation details and showing only functionality to the user. (OR)It highlights the essential things to the user and hides the non- essential things.
Real Time Example:Sending SMS: you just type the text and send the message you don’t know the internal processing about message delivery. Syntax to declare the abstract class: Abstract class < class- name> {
}
ENCAPSULATION
Encapsulation is a process of wrapping code and Data together into a single unit.
We can calculate a fully encapsulated class by making all the data members of the class private now we can use setter and getter methods to set and get the data in it.
In a encapsulated class we can access only the methods we can’t able to access the data that scenario is called Data Hiding.
INHERITANCEInheritance is a mechanism in which one object acquires and the properties and behaviors of parent class. A new class derived from old class.Syntax for Inheritance:
class subclass name extends super class name{
}extends is a key word is used to inherit one class for another class.On the basis of class, there can be three types of inheritance single, multilevel and Hierarchical. Multiple and Hybrid is supported through interface only. To reduce the complexity and simplify the language, multiple interfaces are not supported in Java.
POLYMORPHISMIn general polymorphism is a particular thing behave differently in a different situation
Two types of Polymorphism: Compile time Polymorphism Run time PolymorphismRun time Polymorphism Example: Method Overloading.Compile time Polymorphism Example: Method Overriding.
Real time Example: Mobile Phone: It acts like a phone where you calling to someone. It acts like a camera whiles you taking a snap. It acts like a Music player whiles you hearing song from that.
Run time PolymorphismRun time PolymorphismMethod overloading:Method having same name but difference in the number of arguments and its data type.
Example:Sum( int a, int b)Sum( int a, int b, int c)Sum( float a, float b)Sum( float a, float b, float c)
For example the entire method names are same but the main difference in the number of arguments and its data type.
Compile Time Polymorphism
Method Overriding:
Method having same name, same number of arguments and its data type.
overriding method MUST have the same argument list (if not, it might be a case of overloading)
overriding method MUST have the same return type; the exception is covariant return (used as of Java 5) which returns a type that is a subclass of what is returned by the over riden method
» What is java?
» Introduction about JDK ,JRE,JVM
» Java ME, Java SE, Java EE
» Hello World Example in Android
» Usage of this , Super , final Keyword
» Access Modifiers
» try, catch, finally
INTRODUCTION OF JAVA
What is Java? Java is a programming language and a platform. Java is a case sensitive.
Java is : Object Oriented: In Java, everything is an Object. Java can be easily extended since it is based on the Object model. High Performance: With the use of Just-In-Time compilers, Java enables high performance. Dynamic: Java programs can carry extensive amount of run-time information that can be used to verify and resolve accesses to objects on run-time.
What is JDK?
JDK is an acronym for Java Development Kit.
It contains JRE + development tools. The Java Development Kit (JDK) is a software development environment used for developing Java applications and applets. It includes the Java Runtime Environment (JRE), an interpreter/loader (java), a compiler (javac), an archiver (jar), a documentation generator (javadoc) and other tools needed in Java development.
What is JRE? The Java Runtime Environment (JRE) is a set of software tools for development of Java applications. It combines the Java Virtual Machine (JVM), platform core classes and supporting libraries. JRE is part of the Java Development Kit (JDK), but can be downloaded separately.
JRE was originally developed by Sun Microsystems Inc., a wholly-owned subsidiary of Oracle Corporation. Also known as Java runtime.
What is JVM?What is JVM? A Java virtual machine (JVM) is a virtual machine that can Execute Java byte code.
It is the code execution component of the Java platform. JVM performs four main tasks:
» Loads code
» Verifies code
» Executes code
» Provides runtime environment
What is the difference between JDK,JRE,JVM? Java Virtual Machine (JVM) is an abstract computing machine. Java Runtime Environment (JRE) is an implementation of the JVM. Java Development Kit (JDK) contains JRE along with various development tools like Java libraries, Java source compilers, Java debuggers, bundling and deployment tools.
Hello world Program in Java
Class hello world test{
public static void main(String[] args){
System.out.println(“ Hello World”);
}}
> Class:: is used to declare a class in Java.
> public:: is an access specifires which represents visibilityit means visible to all.
> static:: is a keyword, if we declare any method as static is known as static method. The core of advantage of static method is that there is no need to create object to involve the static method.
> void:: is the return type of the method it means it doesn’t return any value.
> main:: represents start up of the Program.
> String args[]:: is used for command line arguments.
> System.out.println():: is used to print statement.
this (Keyword)In Java this is a reference variable that refers to the current object.
Usage of this Keyword:
>this keyword can be used to refer current class instance variable.
>this keyword can be used to involve current class constructor.
>this keyword can be used to involve current class method.
>this keyword can be passed as an argument in the method call.
>this keyword can be passed as an argument in the constructor
call.
>this can also be used return the current class instance.
Super (Keyword)
Super keyword is a reference variable that is used to refer immediate parent class object.
Usage of super (keyword):
>Super is used to refer immediate parent class instance variable.
>Super() is used to involve immediate parent class constructor.
>Super is used to involve immediate parent class method.
final (keyword)The final keyword in java is used to restrict the user. The final keyword can be Variable Method ClassSyntax:final< variable name> final <method name>();final <class name>{ }If you make any variable as final you cannot change the value of final variable (it will be constant).If you make any method as final you cannot override it.If you make any class as final you cannot extend it.
Access modifiers
The access modifier specifies of a data member, method, constructor or class.
There are 4 types of access modifiers.
> private
> default
> protected
> public
> private:: the private access modifies is accessible only within class.
> protected:: the protected access modifier is accessible within package and outside package but through inheritance only.
The protected access modifier can be applied on the data member, method and constructor; it can’t be applied on the class.
> public:: Public access modifier is accessible everywhere, it has the widget scope among all other modifier.
PRIVATE
DEFAULT
PROTECTED
PUBLIC
Same class
Yes Yes Yes Yes
Same package subclass
No Yes Yes yes
Same Package
Non-subclass
No Yes Yes yes
Different package subclass
No No Yes Yes
Different package
Non-subclass
No No No Yes
Catching ExceptionsA method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code, and the syntax for using try/catch looks like the following:
try { //Protected code }catch(Exception Name e1) { //Catch block }
throws/throw Keywords•If a method does not handle a checked exception, the method must declare it using the throws keyword. The throws keyword appears at the end of a method's signature.•You can throw an exception, either a newly instantiated one or an exception that you just caught, by using the throw keyword. •Try to understand the different in throws and throw keywords.•The following method declares that it throws a RemoteException:
import java.io.*; public class className { public void deposit(double amount) throws RemoteException { // Method implementation throw new RemoteException(); } //Remainder of class definition }
What is Android ?What is Android ?
Android is a Operating System based on Linux Kernel
If any Operating System based on Linux Kernel then no need to install any hardware drivers and all its automatically recognize hardware
In previous days people said like android is a mobile operating system because that time android was working as a operating system only for mobile but now android is working as a Operating system for Smartphone, Tablet ,TVs ,Cameras ,Smart Glasses ,Wristwatches ,Headphones etc…
» The OHA is a group of hardware and software
developers, including Google, NTT DoCoMo,
Sprint Nextel, and HTC …
» OHA have developed Android™, the first
complete, open, and free mobile platform
» Goal
» Accelerate innovation in mobile
» Offer consumers a richer, less expensive, and
better mobile experience
Open Handset Alliance(OHA)
ANDROID HISTORY
•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.
•In 2005 Google purchased Android and took over its development work and also the development team.
•Google wanted Android to be open and free then most of the Android code was released under open source.
VERSIONS OF ANDROIDPre-commercial release versions (2007–2008)
Android alpha
There were at least two internal releases inside Google and the OHAreleases code-named “Astra Boy", “Bender"
Android beta
The Android beta was released on 5 November 2007
The Software Developement Kit (SDK) was released on 12 November 2007.
The 5 November date is popularly celebrated as “Android's Birthday”
VERSIONS OF ANDROID
Android has seen numerous Updates which have incrementally improved the operating system, adding new features and fixing bugs in previous releases.
Each major release is named in alphabetical order after a dessert or sugary treat
For example
Version 1.5 Cupcake was followed by 1.6 Donut.
The latest released version is 4.4 Kit Kat
CUPCAKE 1.5CUPCAKE 1.5
On 30 April 2009, the Android 1.5 update was released.
This was the first release to officially use a codename based on a dessert item ("Cupcake")
»Added auto-rotation option.
»Copy and Paste feature added in the web browser.
»Increased speed and performance but not up to required level.
VERSIONS OF ANDROID
DONUT 1.6DONUT 1.6
On 15 September 2009, the Android 1.6 SDK - Donut was released
»Voice search
»Search box
»Faster OS boot times
»Fast web browsing experience.
»Typing is quite slower.
VERSIONS OF ANDROID
ECLAIR 2.0ECLAIR 2.0On 26 October 2009, the Android 2.0 SDK codenamed Eclair was released.
»Bluetooth 2.1 support.» Improved typing speed on virtual keyboard with smarter dictionary.» no Adobe flash media support.
on 3 December 2009 Android 2.0.1 Éclair was released.
on 12 January 2010 Android 2.1 Éclair was released.
VERSIONS OF ANDROID
FROYO 2.2FROYO 2.2
On 20 May 2010, the SDK for Android 2.2 was released
»Support for Adobe Flash 10.1
» Improved Application launcher
with better browser
» No internet calling.
VERSIONS OF ANDROID
GINGERBREAD 2.3GINGERBREAD 2.3
On 6 December 2010, the Android 2.3 (Gingerbread) SDK was
released
»Updated User Interface with high
»efficiency and speed
» Internet calling
» One touch word selection and copy/paste.
» New keyboard for faster word input.
on 9 February 2011 Android 2.3.3 Gingerbread was released.
on 28 April 2011 Android 2.3.4 Gingerbread was released.
VERSIONS OF ANDROID
HONEYCOMB 3.0HONEYCOMB 3.0On 22 February 2011, the Android 3.0 (Honeycomb) SDK was released
»Support for multi-core processors
» Ability to encrypt all user data.
» This version of android is only available for tablets.
on 10 May 2011 Android 3.1 Honeycomb was released.
on 15 July 2011 Android 3.2 Honeycomb was released.
VERSIONS OF ANDROID
ICE CREAM SANDWICH 4.0ICE CREAM SANDWICH 4.0On 19 October 2011, the Android 4.0 (Ice Cream Sandwich) SDK was released
»Virtual button in the UI.
» A new typeface family for the UI.
» Ability to shut down apps that are using data in the background
on 16 December 2011 4.0.3 Ice Cream Sandwich was released.
on 29 March 2012 4.0.4 Ice Cream Sandwich was released.
VERSIONS OF ANDROID
JELLY BEAN 4.1JELLY BEAN 4.1
On 27 June 2012, the Android 4.1 (Jelly Bean) SDK was released
»User – Installable Keyboard Maps
» Multichannel Audio.
» Bluetooth Data Transfer with Android Beam.
on 29 October 2012 4.2 Jelly Bean was released.
on 24 July 2013 4.3 Jelly Bean was released.
VERSIONS OF ANDROID
KIT KAT 4.4KIT KAT 4.4
On 3 September 2013, the Android 4.4 (Kit Kat) SDK was released
»New Framework for UI Transitions.
» Built-In Screen Recording.
»Wireless printing Capability
VERSIONS OF ANDROID
LOLLIPOP ANDROID 5.0• on June 25, 2014, the android
LolliPop 5.0 was released. • Redesigned user interface built
around a design language known as "Material design".
• Improvements to the notifications, which can be accessed from the lock screen and displayed within applications as top-of-the-screen banners.
ANDROID FEATURESANDROID FEATURES
»STRORAGESQLite, a lightweight relational database.
»CONNECTIVITYSupports GSM, CDMA, Bluetooth, Wi-Fi, WiMAX.
»MESSAGING Supports both SMS and MMS.
»MEDIA SUPPORTSupports following media files: MP3,3GP,MP4,JPEG,PNG,GIF,BMP,AMR,MIDI,...etc.
»HARDWARE SUPPORTAccelerometer sensor, Camera, GPS, Digital compass.
»MULTI TASKINGsupports multi –tasking applications.
Android OS Distribution Details Android OS Distribution Details (As on SEP 2013)(As on SEP 2013)
S.No Version Codename API A
1 1.6 Donut 4 0.20%
2 2.1 Éclairs 7 1.90%
3 2.2 Froyo 8 7.60%
4 2.3 - 2.3.2 Gingerbread 9 0.20%
5 2.3.3 - 2.3.7 10 44%
6 3.1 Honeycomb 12 0.30%
7 3.2 13 0.90%
8 4.0.3 - 4.0.4 Ice Cream Sandwich 15 28.60%
9 4.1 Jelly Bean 16 14.90%
10 4.2 17 1.60%
Android Application Life CycleAndroid Application Life Cycle
» Environment Setup
» Development
» Debugging & Testing
» Deploy
Environment SetupEnvironment Setup
Set up Set up Your Your
Development Development EnvironmentEnvironment
Set up AVD’s Set up AVD’s and Devices for and Devices for
TestingTesting
Install the Android SDK , Android Developer Tools and Android Platform
Create Android Virtual Device and connect Hardware Device that will be used for Testing
DevelopmentDevelopment
CreateCreate YourYour
ApplicationApplication
Create Android Project with your source code, resource files and Android manifest xml file
Debugging & TestingDebugging & TestingBuild and Run Build and Run
Your ApplicationYour Application
Debug your Debug your ApplicationApplication
Build and Run your ApplicationIn Debug Mode
Debug your Applications using the Android Debugging and Logging Tools
Test Your Application using theAndroid Testing and Instrumentation Framework
Test your Test your ApplicationApplication
DeployDeployPrepare your Prepare your
Application for Application for releaserelease
Release Your Release Your ApplicationApplication
Configure ,build and test your application for Release Mode
Publish ,Sell and distribute your Application to users.
Android ArchitectureAndroid Architecture
Android Architecture having Four Main Layer and One Sub Android Architecture having Four Main Layer and One Sub
LayerLayer
»Applications - Main Layer
»Application Framework - Main Layer
»Libraries - Main Layer
»Android Runtime - Sub Layer
»Linux kernel - Main Layer
Android Architecture
Linux Kernel
» Relying on Linux Kernel 2.6 for core system services» Memory and Process Management» Network Stack» Driver Model» Security
» Providing an abstraction layer between the H/W and the rest of the S/W stack
Android Runtime
Core LibrariesProviding most of the functionality available in the core libraries of the Java language
Dalvik Virtual MachineProviding environment on which every Android application runs
LibrariesLibraries
» Including a set of C/C++ libraries used by components of the
Android system
» Exposed to developers through the Android application
framework
Application Framework LayerApplication Framework Layer
Feature RoleView
SystemUsed to build an application, including lists, grids, textboxes, buttons, and embedded web browser
Content Provider
Enabling applications to access data from other applications or to share their own data
Resource Manager
Providing access to non-code resources (localized strings, graphics, and layout files)
Notification Manager
Enabling all applications to display customer alerts in the status bar
Activity Manager
Managing the lifecycle of applications and providing a common navigation backstack
Application LayerApplication Layer
Android provides a set of core applications:
» Email Client
» SMS Program
» Calendar
» Maps
» Browser
» Contacts
Android ArchitectureAndroid Architecture
Function Of DVMFunction Of DVM
*.java *.class *.dex
*.apk
Javac dex
aapk
ADT- Android Developer Tools Eclipse IDE Android SDK ADT Plug-in
Java JDK 1.7
OS RequirementsWindows 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) On Ubuntu Linux, version 8.04 or later is required.64-bit distributions must be capable of running 32-bit applications.
HowHow to set up Android to set up Android EnvironmentEnvironment
How to set up Android How to set up Android EnvironmentEnvironment
Before you are going to download ADT (Android Developer Tools)You have to download and install JAVA JDK from the below link
http://www.oracle.com/technetwork/java/javase/downloads/index.html
After finishing the JAVA installation you have to download ADT form the below link
http://developer.android.com/sdk/index.html
» Unpack the ZIP file (named adt-bundle-<os_platform>.zip) and
save it to an appropriate location, such as a "Development“
directory in your home directory.
» Open the adt-bundle-<os_platform>/eclipse/ directory and
launch eclipse.exe
Android SDKThe Android SDK, which is mandatory in order to create any
Android application, is the kit where all the tools required to
develop any Android project are available.
The following are some among the tools contained by the Android
SDK.
Android Emulator
DDMS (Dalvik Debug Monitor Service)
adb (Android Debug Bridge)
SQLite3
ADT (Android Development Tools) Plug-in
ADT is a plug-in for Eclipse IDE provided by Android.
This extends the capabilities of the Eclipse IDE & makes it a place where we can develop, run & debug Android projects.
Developing Android projects in Eclipse with the help of ADT plug-in is said to be the highly recommended way.
The ADT is not needed if you choose to work in an IDE other than Eclipse.
How To Create a New Android Project
1. Click New in the toolbar.
2. In the window that appears, open the Android folder, select Android Application Project, and click Next.
3. Fill in the form that appears:
• Application Name is the app name that appears to users. For this project, use "My First App.“
• Project Name is the name of your project directory and the name visible in Eclipse.
4. On the next screen to configure the project, leave the default selections and click Next.
5. The next screen can help you create a launcher icon for your app. You can customize an icon in several ways and the tool generates an icon for all screen densities. Before you publish your app, you should be sure your icon meets the specifications defined in the Iconography design guide.Click Next.6. Now you can select an activity template from which to begin building your app.For this project, select Blank Activity and click Next.
7. Leave all the details for the activity in their default state and click Finish.
Android Application Project Structure
Whether you're using Eclipse or the command line, to run your app on the emulator you need to first create an Android Virtual Device (AVD). An AVD is a device configuration for the Android emulator that allows you to model different devices.
How To Create a New AVD(Android Virtual Device)
To create an AVD:1. Launch the Android Virtual Device Manager:
a. In Eclipse, click Android Virtual Device Manager from the toolbar.
2. In the Android Virtual Device Manager panel, click New.
3. Fill in the details for the AVD. Give it a name, a platform target, an SD card size, and a skin (HVGA is default).
4. Click Create AVD.
5. Select the new AVD from the Android Virtual Device Manager and click Start.
6. After the emulator boots up, unlock the emulator screen.
Components of AndroidComponents of Android
» Activity
» Services
» Broadcast Receiver
» Content Providers
Activities
Visual user interface focused on a single thing a user can do
Services
`No visual interface – they run in the background
Broadcast Receivers
Receive and react to broadcast announcements
Content Providers Allow data exchange between applications
» Basic component of most applications» Most applications have several activities that start each other as
needed
» Each is implemented as a subclass of the base Activity class
» Each activity has a default window to draw in.
» The content of the window is a view or a group of views.
» View(Group) made visible via Activity.setContentView() method.
Activities
Services
» Does not have a visual interface
» Runs in the background indefinitely
» Examples
» Network Downloads
» Playing Music
» You can bind to a an existing service and control its
operation
Broadcast Receiver
» Receive and react to broadcast announcements
» Extend the class Broadcast Receiver
» Examples of broadcasts:
» Low battery, power connected, shutdown, time zone
changed, etc.
» Other applications can initiate broadcasts
Content Providers
» Makes some of the application data available to other applications
» It’s the only way to transfer data between applications in Android
(no shared files, shared memory, pipes, etc.)
» Extends the class Content Provider;
» Other applications use a Content Resolver object to access the data
provided via a Content Provider
Activity Life Cycle
Each application runs in its own process.
Each activity of an app is run in the apps process
Processes are started and stopped as needed to run an apps
components.
Processes may be killed to reclaim needed resources.
Killed apps may be restored to their last state when
requested by the user
Most management of the life cycle is done automatically by the system via the activity stack.
The activity class has the following method callbacks to
help you manage the app:–onCreate()–onStart()–onResume()–onPause()–onStop()–onRestart()–onDestroy()
• Activities have
several states
• Lifecycle methods are
called on transitions
• You typically don’t
need to use them all,
but they are there
DDMSDalvik Debug Monitor Service, a GUI debugging application shipped with the SDK. It provides screen capture, log dump, and process examination capabilities.Viewing heap usage for a process
DDMS allows you to view how much heap memory a process is using. This information is useful in tracking heap usage at a certain point of time during the execution of your application.Tracking memory allocation of objects
DDMS provides a feature to track objects that are being allocated to memory and to see which classes and threads are allocating the objects.
LOGCATLogcat is integrated into DDMS, and outputs the messages that you print out using the Log class along with other system messages such as stack traces when the exceptions are thrown.Emulating phone operations and location
The emulator control tab lets you simulate a phone’s voice and data network status. This is useful when you want to test your application’s robustness in differing network environments.
Changing network state, speed, and latencyThe Telephony Status section of the Emulator controls tab
lets you change different aspects of the phone’s networks status, speed and latency.
Voice - unregistered, home, roaming, searching, deniedData - unregistered, home, roaming, searching, denied Speed - Full, GSM, HSCSD, GPRS, EDGE, UMTS, HSDPALatency - GPRS, EDGE, UMTS Spooling calls or SMS text messages
The Telephony Actions section of the emulator controls tab lets you spoof calls and messages.
•Voice - Enter a number in the incoming number field and click call to send a simulated call to the emulator or phone Click the Hang up button to terminate the call.
•SMS - Enter a number in the incoming number field and a message in the Message: field and click the Send button to send the message
Setting the location of the phone
If your application depends on the location of the phone, you can have DDMS send your device or AVD a mock location.
•Manual - set the location by manually specifying decimal longitude and latitude values.
•GPX - GPS eXchange file
•KML - keyhole Markup Language file
• Database is saved in the device’s memory
Views
An Activity contains Views and View Groups.
A View is a widget that has an appearance on screen.
A view derives from the base class android.view.View
Examples of views are buttons, labels and text boxes.
Textview Syntax:
TextView tv;
tv = (TextView) findViewById(R.id.textview);
tv.setText(“ Textview is displayed ”);
Button Syntax:
Button button;
button.setOnClickListener(new OnClickListener()
{
@override
public void onClick(View arg0)
{
tv.setText(“You Clicked Button”);
}
});
View Groups
A ViewGroup provided a layout in which the order and
appearance of the views are placed.
A view derives from the base class android.view.ViewGroup.
Android supports the following ViewGroups,
LinearLayout RelativeLayout
AbsoluteLayout TableLayout
FrameLayout ScrollView
Linear LayoutArranges views in a single column
or single row.
Absolute LayoutEnables to specify the exact location of its
children.
Table LayoutGroups views into rows and columns.
Relative LayoutEnables us to specify how child views are positioned relative to each other.
Frame LayoutPlaceholder on screen to display as a single
view.
Sample xml for a Layout ……<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@layout/roundedcorner">
<ImageView android:id="@+id/Icon" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/someImage"> </ImageView></LinearLayout>
1.Landscape.
2.Portrait.
• One of the key features of modern smartphones is their ability to switch screen orientation.
• Android supports two screen orientations– portrait – Landscape
• When you change the orientation of your Android device, your current activity is actually destroyed and then re-created.
• You can employ two techniques to handle changes in screen orientation– Anchoring– Resizing and repositioning
• Resizing and Repositioning
– customize the UI based on screen orientation is to create a
separate res/layout folder containing the XML files for the UI
of each orientation.
– To support landscape mode, you can create a new folder in the
res folder and name it as layout-land (representing landscape).
– The main.xml file contained within the layout folder defines
the UI for the activity in portrait mode, whereas the main.xml
file in the layout-land folder defines the UI in landscape mode
• Use the WindowManager class to know the device’s current orientation during run time.
//---get the current display info---WindowManager wm = getWindowManager();Display d = wm.getDefaultDisplay();if (d.getWidth() > d.getHeight()){//---landscape mode---}else{//---portrait mode---}
• You can programmatically force a change in orientation using
the setRequestOrientation() method of the Activity class.
– setRequestedOrientation(ActivityInfo.SCREEN_ORIENTAT
ION_LANDSCAPE);
– setRequestedOrientation(ActivityInfo.SCREEN_ORIENTAT
ION_PORTRAIT);
• You can also use the android:screenOrientation attribute on
the <activity> element in AndroidManifest.xml
Three of the core components of an Android application -
activities, services, and broadcast receivers - are activated
through messages, called intents
One activity starts another activity by creating/sending an
Intent
Means of leveraging activities, services, and broadcast
receivers of other applications .
Explicit intents
Designate the target component by its class (the component
name field is set by the class name)
Since component names (class name of the target activity,
for example) would generally not be known to developers
of other applications, explicit intents are typically used for
application-internal messages — such as an activity starting
a subordinate service or launching a sister activity.
Syntax for Explicit Intent:
// Explicit Intent by specifying its class name Intent i = new Intent(this, TargetActivity.class);
i.putExtra("Key1", "ABC");
i.putExtra("Key2", "123");
// Starts TargetActivity
startActivity(i);
Implicit intents
Do not name a target (the component name field is blank).
Implicit intents are often used to activate components in other
applications.
Syntax for Implicit Intent:
// Implicit Intent by specifying a URI
Intent i = new Intent(android.content.Intent.ACTION_VIEW,
uri.parse("http://www.example.com"));
// Starts Implicit Activity
startActivity(i);
Value Passing using IntentWe can pass the values by using Intent and Bundle.Value passing by intent:
We can pass values from activity to another activity using Intent.Syntax:
Intent i = new (context, destination.class);// we can put the values using “putExtra” method
i.putExtra(“key1”,”Target”);startActivity(i);
//We can get the value in other activity using below syntaxgetIntent().getCharSequenceExtra (“key1”).toString();
Value passing by Bundle:We can also pass values from activity to another
activity using Bundle.
Syntax:Intent i = new (context, destination.class);Bundle b = new Bundle();b.putCharSequence(“key1”,”android”);i.putExtra(b);startActivity(i);
//We can get the value in other activity using below syntax getIntent().getExtra().getCharSequenceExtra(“key1”).toString();
Difference between Intent & Bundle:
When we are passing values directly through Intent, there is a chance of missing values.
So, it is better to pass values through Bundle, because in bundle there is no chance of missing values.
Toast
Toast can be used to display information for the short period of time.
Toast class is used to show notification for a particular interval of time. After sometime it disappears. It doesn't block the user interaction.
Toast.maketext(Context context, CharSequence text, int duration)
Parameters:context : The context to use. Usually your Application or
Activity object
text : The text to show. Can be formatted text.
duration : How long to display the message.
Either LENGTH_SHORT or LENGTH_SHORT
Example:
Toast.makeText(getApplicationContext(),"Hello World",Toast.LENGTH_SHORT).show();
Custom ToastYou are able to create custom toast in android. So, you
can display some images like congratulations or loss on the toast.
• It means you are able to customize the toast now.
Toast toast = new Toast(displayContext);
toast.SetText(stringText);
toast.SetGravity (GravityFlags.Top, offsetX, offsetY);
//toast.Show;
Example:
Toast toast = new Toast(getApplicationContext()); toast.setDuration(Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setView(layout);//setting the view of custom toast layout toast.show();
• An AlertDialog is an extension of the Dialog class.
• It should be used for dialogs that use any of the following features:– A title– A text message– One, two, or three buttons– 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().
Alert Dialog
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(); } })
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } });AlertDialog alert = builder.create();
Custom Alert Dialog• Dialog is like a popup window to show some options to users(options like accept/decline).Using class android.app.Dialog to create dialog.Using dialog.xml file to create custom dialog layout.Functionality:Context context=getApplicationContext();Dialog dialog=new Dialog(context);
• dialog.setTitle("Dialog Title");• dialog.requestWindowFeature(Window.FEATURE_NO_
TITLE);
• Notification is just to notify some incoming mails and login status of friends etc…
• Have to import these packages import android.app.Notification;Import android.app.NotificationManager;
•A Notification is a short message breifly displayed on the status line.
• It typically announces the happening of an special event for which trigger has been set.
NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Notification nd = new Notification(R.drawable.ic_launcher,"Alert",System.currentTimeMillis());
Intent I = new Intent(android.content.Intent.ACTION_VIEW,Uri.parse("http://www.google.co.in"));
PendingIntent pi = PendingIntent.getActivity(MainActivity.this, 0, i, android.content.Intent.FLAG_ACTIVITY_NEW_TASK);
nd.setLatestEventInfo(MainActivity.this, "Just Click me","Go to Google page" , pi);nm.notify(0,nd);
Spinner
• Spinner is like the combo box of AWT or Swing. It can be used to display the multiple options to the user.
• Only one item can be selected by the user.
Example:
ArrayAdapter aa = new ArrayAdapter(this,android.R.layout.simple_spinner_item,country);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Syntax:
Spinner spinner = (Spinner) findViewById(R.id.spinner);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,R.array. planets_array,android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
ListView ListView is a view group that displays a list of scrollable items.
The list items are automatically inserted to the list using an Adapter that pulls content from a source such as an array or database query and converts each item result into a view that's placed into the list.
Example:ListView listview;ArrayAdapter adp = new ArrayAdapter(this,android.R.layout.
simple_list_item_1,country); listview.setadapter(adp);
Syntax:
ListView listview = (ListView) findViewById(R.id.listview);
// Create an ArrayAdapter using the string array and a default listview layout
ArrayAdapter<CharSequence> adapter =
ArrayAdapter.createFromResource(this,R.array. planets_array,android.R.layout.simple_list_item);
// Apply the adapter to the listview
listview.setAdapter(adapter);
• Types of application menus:
Options Menu
The options menu is the primary collection of menu
items for an activity. It's where you should place actions that
have a global impact on the app, such as "Search," "Compose
email," and "Settings.“
Context Menu
A floating list of menu items that appears when
the user touches and holds a view that's registered to provide a
context menu.
Menus in Android
Plus
Home
Pre
Next
<option menu>
Sub1
Sub2
Hi
Hola
Hello
<sub-menu>
<context menu from EditText>
Long press in EditText
Submenu
A floating list of menu items that appears
when the user touches a menu item that contains a
nested menu.
• <menu>– Defines a Menu, which is a container for menu items– A <menu> element must be the root node for the file and can
hold one or more <item> and <group>elements• <item>
– Creates a MenuItem, which represents a single item in a menu.
– This element may contain a nested <menu> element in order to create a submenu.
• <group>– An optional, invisible container for <item> elements.– It allows you to categorize menu items so they share
properties such as active state and visibility
Media Player
MediaPlayer class can be used to control playback of audio/video files and streams. Playback control of audio/video files and streams is managed as a state machine.
• Public static MediaPlayer create (Context context,URI uri)
• Added in API level 1
• Convenience method to create a MediaPlayer for a given Uri. On success, prepare() will already have been called and must not be called again.
When done with the MediaPlayer, you should call release(), to free the resources. If not released, too many MediaPlayer instances will result in an exception.
Parameters
Context the Context to use uri the Uri from which to get the data source holder the SurfaceHolder to use for displaying the video
Returns
a MediaPlayer object, or null if creation failed
Supported Media FormatsAudio Format :
3GPP (.3gp)
MPEG-4 (.mp4, .m4a)
ADTS raw AAC (.aac, decode in Android
3.1+, encode in Android 4.0+, ADIF not
supported)
MP3 (.mp3)
WAVE (.wav)
MediaPlayer mp = new MediaPlayer();// Set data source -setDataSource("/sdcard/path_to_song");// Play audiomp.start();// Pause audiomp.pause();// Reset mediaplayermp.reset();// Get song length duration - in millisecondsmp.getDuration();// Get current duration - in millisecondsmp.getCurrentDuration();// Move song to particular second - used for Forward or Backwardmp.seekTo(positon); // position in milliseconds// Check if song is playing or notmp.isPlaying(); // returns true or false
Audio Player
VideoView videoView =(VideoView)findViewById(R.id.videoView);MediaController mediaController= new MediaController(this);mediaController.setAnchorView(videoView); Uri uri=Uri.parse("android.resource://"+getPackageName()+"/"+R.raw.one); videoView.setMediaController(mediaController); videoView.setVideoURI(uri); videoView.requestFocus(); videoView.start(); videoView.stopPlayback();videoView.pause();videoView.isPlaying(); videoView.getDuration();videoView.getCurrentPosition();
Video Player
Services• Run in the background
• Can continue even if Activity that started it dies• Should be used if something needs to be done while the
user is not interacting with application• Otherwise, a thread is probably more applicable• Should create a new thread in the service to do work in,
since the service runs in the main thread
• Can be bound to an application• In which case will terminate when all applications bound
to it unbind• Allows multiple applications to communicate with it via a
common interface• Needs to be declared in manifest file
• Like Activities, has a structured life cycle
Service Life Cycle
ServicesNormally Services are two types, they are
1.Synchronous Service
2.Asynchronous Service
Synchronous Service:Service is an application component
representing either an application desire to perform a long-running operations while not interacting with the user or to supply functionality for other application to use.
In synchronous service we are using mainly 6 methods.
1. OnCreate()2. OnStartCommand()3. OnBind()4. OnUnbind()5. OnRebind()6. OnDestroy()
Example:
Public void onCreate(){
// TODO Auto-generated method stubsuper.onCreate();
}
@Override public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
return super.onStartCommand(intent, flags, startId);
}
@Overridepublic void onDestroy() {
super.onDestroy();
}
Asynchronous Service:AsyncTask is a abstract class provided by android
which helps us to use the UI thread proparly.
This class allows us to perform long/background operations and show its result on the UI thread without having to manipulate thread.
In Asynchronous service we are using 4 Steps.
1. OnPreExecute() 2. OnDoInBackground() 3. OnProgressUpdate() 4. OnPostExecute()
In AsyncTask we are using only 2 methods, they are1. OnCreate()2.OnStartCommand()Example:protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);
tv = (TextView)findViewById(R.id.textView1Sampleayntask);
new SampleTask().execute();}
private class SampleTask extends AsyncTask<Void, Integer, Void>{ @Override protected void onPreExecute() { tv.setText("******** Countdown Starts ********"); }
@Overrideprotected Void doInBackground(Void... params){
return null;}protected void onProgressUpdate(Integer... values)
{tv.setText( Integer.toString(values[0].intValue()));
} @Override protected void onPostExecute(Void result) {
tv.setText("******** DONE ********");
}}
• Broadcast Receivers simply respond to broadcast messages from other applications or from the system itself.
• These messages are sometime called events or intents.
• For example, applications can also initiate broadcasts to let other applications know that some data has been downloaded to the device and is available for them to use, so this is broadcast receiver who will intercept this communication and will initiate appropriate action.
• There are following two important steps to make BroadcastReceiver works for the system broadcasted intents. < Creating the Broadcast Receiver.< Registering Broadcast Receiver
Broadcast Receiver
Creating the Broadcast Receiver:
A broadcast receiver is implemented as a subclass of BroadcastReceiver class and overriding the onReceive() method where each message is received as a Intent object parameter.
public class MyReceiver extends BroadcastReceiver {
@Override public void onReceive(Context context, Intent
intent) { Toast.makeText(context, "Intent Detected.",
Toast.LENGTH_LONG).show(); }
}
Registering Broadcast Receiver:An application listens for specific broadcast intents by registering a broadcast receiver inAndroidManifest.xml file.
•Consider we are going to register MyReceiver for system generated event ACTION_BOOT_COMPLETED which is fired by the system once the Android system has completed the boot process.
<receiver android:name="MyReceiver"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED"> </action> </intent-filter> </receiver>
• An Intent-based publish-subscribe mechanism.
• Great for listening system events such as SMS messages.
Android
System
Broadcast Receiver
1.Register for
Broadcast Intent
2.OnReceive()
• Using SQL databases in Android:
– Android (as well as iPhoneOS) uses an embedded standalone
program called sqlite3 which can be used to:
• create a database, define SQL tables, indices, queries,
views, triggers , Insert rows, delete rows, change rows,
run queries and administer a SQLite database file .
• A way of opening/creating a SQLITE database in your
local Android’s data space is given below
SQLite Database
SQLiteDatabasedb = this.openOrCreateDatabase("myfriendsDB", MODE_PRIVATE, null);
• where the assumed prefix for the database stored in the devices ram is: "/data/data/<CURRENT_namespace>/databases/".
• For instance if this app is created in a namespace called “cis493.sql1”, the full name of the newly created database will be: “/data/data/cis493.sql1/databases/myfriendsDB”.
• This file could later be used by other activities in the app or exported out of the emulator (adbpush…) and given to a tool such as SQLITE_ADMINISTRATOR.
SQLite Database
• Database is saved in the device’s memory
• MODEcould be: MODE_PRIVATE, MODE_WORLD_READABLE, and MODE_WORLD_WRITEABLE. Meaningful for apps consisting of multiples activities.
SQLite Database
• Once created, the database is ready for normal operations such as:– creating, altering, dropping resources (tables, indices,
triggers, views, queries etc.) or administrating database resources (containers, users, …).
• Actionqueries and Retrievalqueries represent the most common operations against the database. – A retrieval query is typically a SQL-Select command in
which a table holding a number of fields and rows is produced as an answer to a data request.
– An actionquery usually performs maintenance and administrative tasks such as manipulating tables, users, environment, etc.
SQLite Database
• We will use the execSQL(…)method to manipulate SQL action queries. The following example creates a new table called tblAmigo.
• The table has three fields: a numeric unique identifier called recID, and two string fields representing our friend’s nameand phone. If a table with such a name exists it is first dropped and then created anew. Finally three rows are inserted in the table.
SQLite Database
• In order to process the resulting rows, the user should provide a cursor device. Cursors allow a row-by-row access of the records returned by the retrieval queries.
• Android offers two mechanisms for phrasing SQL-select statements: rawQueries and simplequeries. Both return a database cursor. – Raw queries take for input a syntactically correct SQL-select
statement. The select query could be as complex as needed and involve any number of tables (remember that outer joins are not supported).
– Simple queries are compact parametized select statements that operate on a single table (for developers who prefer not to use SQL).
SQLite Database
• Using arguments.Assume we want to count how many friends are
there whose name is ‘BBB’ and their recID> 1. We could use the
following construction
String mySQL= "select count(*) as Total "
+ " from tblAmigo"
+ " where recID> ?"
+ " and name = ?";
String[] args= {"1", "BBB"};
Cursor c1 = db.rawQuery(mySQL, args);
SQLite Database
• query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy)
The method’s signature has a fixed sequence of seven arguments representing:
– the table name, – the columns to be retrieved, – the search condition (where-clause), – arguments for the where-clause, – the group-by clause, – having-clause, and – the order-by clause.
SQLite Database
• The Cursor class includes a number of navigation functions :– moveToFirst : Moves the cursor to the first row in the query
result– moveToNext : Moves the cursor to the next row– moveToPrevious : Moves the cursor to the previous row– getCount : Returns the number of rows in the result set– getColumnIndexOrThrow :Returns the index for the column
with the specified name (throwing an exception if no column exists with that name)
– getColumnName : Returns the name of the specified column index
– getColumnNames :Returns a string array of all the column names in the current Cursor
– moveToPosition : Moves the Cursor to the specified row
SQLite Database
• To create a new row, construct a ContentValues object and use its put methods to provide a value for each column.
• Insert the new row by passing the Content Values object into the insert method called on the target database — along with the table name.// Create a new row of values to insert.ContentValues newValues = new ContentValues();// Assign values for each row.newValues.put(COLUMN_NAME, newValue);[ ... Repeat for each column ... ]// Insert the row into your tablemyDatabase.insert(DATABASE_TABLE, null, newValues);
SQLite Database
• Updating rows is also done with Content Values.• Create a new ContentValues object, using the put methods to assign new
values to each column you want to update.• Call update on the database, passing in the table name, the updated
Content Values object, and a where clause that specifies the row(s) to update.
// Define the updated row content.ContentValues updatedValues = new ContentValues();
// Assign values for each row.newValues.put(COLUMN_NAME, newValue);
[ ... Repeat for each column ... ]String where = KEY_ID + "=" + rowId;
// Update the row with the specified index with the new values. myDatabase.update(DATABASE_TABLE, newValues, where, null);
SQLite Database
• To delete a row simply call delete on a database,
specifying the table name and a where clause
that returns the rows you want to delete.
myDatabase.delete(DATABASE_TABLE,
KEY_ID + "=" + rowId, null);
SQLite Database
• * If you want to share data with other applications you can use a ContentProvider.
• * A ContentProvider allows applications to access data.
• * The access to a ContentProvider is done via an URI (Uniform Resource Identifier). The basis for the URI is defined in the declaration of the ContentProvider in the AndroidManifest.xml file via the android:authorities attribute.
• * Many Android data sources, e.g. the contacts, are accessible via ContentProviders. Typically the implementing classes for a ContentProviders provide public constants for the URIs.
Content Provider
Some of the useful Content Providers are, Browser – Stores data such as browser
bookmarks, history CallLog – Stores data such as missed calls, call
details. Contacts – Stores Contact Details MediaStore – Stores media files such as audio,
video and images Settings – Stores the settings of the device and
preferences. Format of the query string URI (Uniform
Resource Identifier) <Standard Prefix
>://<authority>/<data_path>/<id>
Content Provider
Content Provider
public final Cursor managedQuery (Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) Parameters:uri --The URI of the content provider to query.projection --List of columns to return.selection --SQL WHERE clause.selectionArgs --The arguments to selection, if any ?s are presentsortOrder --SQL ORDER BY clause. Returns:The Cursor returned by query ().
Content Provider
import android.provider.CallLog;import android.database.Cursor; // Form an array specifying the columns to return.String[] callLogColumnList = new String[] { CallLog.Calls.NUMBER, CallLog.Calls.CACHED_NAME, CallLog.Calls.DATE, CallLog.Calls.DURATION, CallLog.Calls.TYPE }; // Get the base URI for the People table in the Contacts content provider.Uri callLogs = CallLog.Calls.CONTENT_URI;Uri callLogs = Uri.parse(“content://call_logs/calls”);
Content Provider
// Make the query.Cursor managedCursor = managedQuery (callLogs, callLogColumnList, // which columns to return null, // Which rows to return (all rows) null, // Selection arguments (none) CallLog.Calls.DATE + "DESC" //results in descending order by date);
Content Provider
ChennaiPrithviraj
Target Soft systems8/3, Sarojini Street,
T. Nagar, Chennai – 17.Tel: +91-44-2433 3393.Mob: 91-93 823 83393