1-Introduction to Android:-
Android is a software stack for mobile devices which includes an operating system, middleware and same key application, initially developed by android inc(Incorporation(business)) and it was bought by Google in 2005. It is based upon a modified version of the Linux kernel. It is an open source, which encourage the new developers and third party to develop the new applications. Google and other members of OHA(Open Handset Alliance) collaborated on android’s development and release. Android OS is world’s selling smart Phone platform, dethroning Nokia’s Symbian from the 10-Year top position. Android market is online apps store run by Google. Developers write primarily in java language, controlling the device via Google-developed java library. Android OS uses SQLite (a relational database) for storage purpose.
·
The Evolution of Android/Android
Time Line:-
- October 2003- Android, inc. was founded in Palo Alto, California, US(United States) by Andy Bubin, Rich Miner, Nick and Chris White.
- July 2005- Google acquired Android, INC.
- November 2007- OHA(Open Handset Alliance) was formed and Android was launched.
- October 2008- Android was open sourced.
- October 2008 T-Mobile company announced the G-1 Android mobile phone.
AndroidVersion API Level Version Code Release Data
1.0 1 Apple Pie 23-Sep-2008
1.1 2 Banana Bread 9-Feb-2009
1.5 3 Cupcake 30-Apr-2009
1.6 4 Donut 15-Sep-2009
2.0 5 Éclair 26-Oct-2009
2.1 6 Eclair_0_1 3-Dec-2009
2.1.X 7 Éclair MR1 12-Jan-2010
2.2 8 Froyo 20-May-2010
2.3- 2.3.1- 2.3.2 9 Gingerbread 6-Dec-2010
2.3.3- 2.3.4 10 Ginger MR1 9-Feb-2011
3.0 11 Honeycomb 22-Feb-2011
3.1.x 12 Honey MR1 10-May-2011
3.2.x 13 Honey MR2 15-Jul-2011
4.0.1- 4.0.2 14 Ice
Cream Sandwich 9-Oct-2011
4.0.3-4.0.4 15 Ice Cream Sandwich MR1 16-Dec-2011
4.1 16 Jelly Bean 27-Oct-2012
4.1.2 16 Jelly Bean 9-Oct-2012
4.2 17 Jelly Bean 13-Nov-2012
4.3 18 Jelly Bean 24-Jul-2013
4.4 19 KitKat 31-Oct-2013
4.2 17 Jelly Bean 13-Nov-2012
4.3 18 Jelly Bean 24-Jul-2013
4.4 19 KitKat 31-Oct-2013
Devices Running Android:-
1-HTC Devices:- HTC Dream, HTC Hero, HTC Desire, HTC Sensation.
2-Samsung Devices:- Galaxy Ace, Galaxy Fit, Galaxy Nexus, Nexus S.
3-Motorola Devices:- Motorola Backflip, Motorola Defy, Droid Bionic.
4-Tablets:- Acer
Iconia, Dell Streak, Motorola Zoom Samsung Galaxy Tab, Sony Tablet S.
5-Other Devices:- Acer Aspire One Netbooks, Samsung Galaxy Player, Google TV.
D
DAndroid Layers:-
1- Linux Kernel:- Android‘s kernel is a fork of the
Linux kernel. Android uses Linux version
2.6 for core system services such as security, process management, memory
management, network stack and driver model. The kernel also acts as an
abstraction layer between the hardware and the rest of the software stack.
2.6 for core system services such as security, process management, memory
management, network stack and driver model. The kernel also acts as an
abstraction layer between the hardware and the rest of the software stack.
2-Libraries:- Running on the top of Kernel, Android includes a set of C/C++
libraries used by
various components of the Android system.These capabilities are exposed
to developers through the Android application framework.
various components of the Android system.These capabilities are exposed
to developers through the Android application framework.
3-Android Run-time:- Implementation of Linux is Android run-time
Every Android application
runs in its own process, with its own instance of the DVM.
runs in its own process, with its own instance of the DVM.
4-DVM (Dalvik Virtual Machine):- It’s an
open-source software. DVM is a register base
virtual machine develop by Dan Bornstein. It’s optimized version
of the JVM(Java Virtual Machine). It’s the software that runs the apps
on Android Devices. The compact Dalvik Executable format is
designed to be suitable for systems that are constrained in terms of
memory and processor speed. The DVM relies on the Linux Kernel for
underlying functionality such as threading and low-level memory
management.
virtual machine develop by Dan Bornstein. It’s optimized version
of the JVM(Java Virtual Machine). It’s the software that runs the apps
on Android Devices. The compact Dalvik Executable format is
designed to be suitable for systems that are constrained in terms of
memory and processor speed. The DVM relies on the Linux Kernel for
underlying functionality such as threading and low-level memory
management.
Note:- Dalvik is a
name of a Town in Iceland.
JVM
compatible
DVM compatible
.class
files
.dex files
Downloading and Installing the
Android SDK:-
System Requirements:-
Supported Operating Systems
- Windows XP(32-bit), Vista(32/64-bit), Windows-7(32/64-bit).
- Mac OS X 10.5.8 or later (x86 only).
- Linux (tested on Ubuntu Linux, Lucid Linux)
- C Library (glib) 2.7 or later is required.
- On Ubuntu Linux, Version-8.04 or later is required.
- 64-bit distributions must be capable of running 32-bit applications.
Installing the Android Eclipse
and SDK:-
- Downloading the SDK Starter package from
- Download the JDK and install it.
- Accept License Agreement,
- Installing the ADT Plug-in for Eclipse
- Adding platforms and other components
Downloading the SDK Starter package from
2. Download the JDK and install it.
Setting the JDK path:-
· Click Advanced and also click Environment Variables-
Setting the JDK path:-
· Open My Computer property
· Click advanced system settings
· Click Advanced and also click Environment Variables-
·
Click
New button and setting the JDK path-
- Click Edit button and Edit the SDK tools and platform-tools path
·
Android Development Environment:-
Specify Android
SDK Location for Eclipse
·
Click Window
·
Click Preferences
·
Set androidSDK
path
Configuring Emulator
Click Android SDK and AVD Manager
·
Select Virtual
Devices And click New but
·
Create AVD –AVD Name,
Select Target, SD
Card, Skin and click the Create AVD button
Testing Emulator- Select AVD name and click start button,
Click on start…
3-Installing ADT for Eclipse
- Android Development tools (ADT) is a plug-in for the eclipse IDE.
- Provides a powerful, integrated environment to build Android application.
Downloading the ADT plug-in
1-
Start
Eclipse, then select Help and click Install new software.
2-
Click
Add, in the top-right corner.
3-
In the
Add repository dialog that appears, enter “ADT Plug-in” for the Name and the
following URL for the Location://dl-ssl.google.com/android/eclipse/
4-
In the Available software dialog, select the
tools to be downloaded and click Next.
5-
In the
Next window, you will see a list of the tools to be downloaded and click Next.
6-
Read and
accept the license agreements, then Finish.
Note:- If you get a security warning saying
that the authenticity or validity of the software can’t be established and
click Ok.
7-
When the
installation completes, restart Eclipse.
4-.Adding platforms and other
components
·
The main component that comprise a typical
Android debugging Emulator ,
1-ADB and
2-DDMS.
1-ADB
ADB stand for ‘Android
Debugging Bridge’. ADB are used for communication between Device and
Development System. ADB are provides a command line debugging interface to
running Android phone and Emulator. ADB tool available at
<sdk>/platform-tools/. ADB is a client-server program that includes three
components:-
i.
A
client, which runs on your development machine.
ii.
A
server, which runs as a background process on your development machine.
iii.
Daemon,
which run as a background process on each emulator or device instance.
Open
Command and type adb
1-DDMS:-
Stand for DDMS “Dalvik
Debug Monitor Server”. Android also provides a special window-oriented
debugging environment custom tailored for Android and DVM.
·
Open
eclipse and click DDMS
Soon it will start…..
Creating
Hello Project……
File->> New- >> Android Project
·
Creates a new Android project resource -Project Name
·
Select Contents
and select Build Target and click the finish button
·
Creating Android project Name Hello
Auto-generated file in Eclipse
·
gen/R.java:- This file is automatically generated by Android Developer
Tools and "connects" the resources to
the Java source code.
the Java source code.
·
default.properties:- Contains
project
There are many Source code
·
First.java:-
This implements an Android activity, the primary entry point to the sample
application of this tutorial.
·
Main.xml:-
This contains the visual elements, or resources, for use by Android First activities.
·
AndroidManifest.xml:-
This lists a full AndroidManfest.xml file, along with a description of each of
the important elements.
Running the program:-
·
Right click Hello
project name and select Run As and click 1 Android Application
Output…..
2-Hello World Application:-
Examining the Android-Running the application on Android emulator.
File->>
New->> Android project->> Project Name->> HelloFriend->> Next ->> Select Build Target->> Android
2.3.3->> Next->> Package Name->> com.azeem.hello->> Finish
Click Hello Android file name->> layout->> Main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="HelloFriend" />
</LinearLayout>
Click src->> com.azeem.hello ->>HelloFriendActivity.java
package com.azeem.hello;
import android.app.Activity;
import android.os.Bundle;
public class HelloFriendActivity extends Activity {
import android.app.Activity;
import android.os.Bundle;
public class HelloFriendActivity extends Activity {
/** Called when the activity is first created. */
TextView HelloFriend;
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);
HelloFriend=(TextView)findViewById(R.id.textView1);
}}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tech.azeem"
android:versionCode="1"
android:versionName="1.0"
>
<uses-sdk android:minSdkVersion="10"
/>
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:label="@string/app_name"
android:name=".HelloFriend"
>
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name=
"android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
And
Run HelloFriend file
3-The Android Application Fundamentals
·
Activity/ Lifecycle of Activity:_ An activity represents single screen with a user interface. It have visible interface and this are action class to perform any operation. Activity is an visible components, that use to receive input & to display same output to the user. You can start an activity by passing an Intent to startActivity() or startActivityForResult().
Activity/ Lifecycle of Activity:_ An activity represents single screen with a user interface. It have visible interface and this are action class to perform any operation. Activity is an visible components, that use to receive input & to display same output to the user. You can start an activity by passing an Intent to startActivity() or startActivityForResult().
Life cycle of Activity
There are using three state in
Activity Lifecycle-
1- Active,
2- Visible,
3- Inactive
1- Active Activity-
An active activity
has user focus.
Lifecycle of
an activity is
manage by onResume() & onPouse() call
by method.
2- Visible Activity-
An activity
is visible state
when it is
visible & does
not have user
focus.
Lifecycle of visible
activity are manage
by onStart() & onStop().
3- Inactive Activity-
An activity inactive when
it is not
visible & does
not user focus.
Lifecycle of inactive is manage
by onCreate() & onDestroy() call
by method.
Example:-
File->> New->> Android
project->> Project Name->> Hello Activity->> Next
->> Select Build Target->> Android 2.3.3->> Next->>
Package Name->> com.azeem.activity->> Finish
Click Hello Android file
name->> res->> layout->> main.xml
Main.xml
<?xml version="1.0"
encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
>
<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
</EditText>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
/>
</LinearLayout>
HelloActivity.java
package
com.tech.azeem;
import android.app.Activity;
import
android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import
android.widget.Button;
import android.widget.EditText;
public class
HelloAzeemActivity extends Activity implements
OnClickListener{
EditText
editText;
Button button;
Button button;
public void
onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.main);
editText=(EditText)findViewById(R.id.editText1); button=(Button)findViewById(R.id.button1); button.setOnClickListener(this)
}
public void onClick(View
v) {
String
string=editText.getText().toString(); editText.setText("HelloActivity"+string);
}}
}}
HelloActivityManifest.xml
<?xml version="1.0"
encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tech.azeem"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="10"
/>
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:label="@string/app_name"
android:name=".HelloActivity" >
<intent-filter >
<action android:name="android.intent.action.MAIN"
/>
<category android:name="android.intent.category.LAUNCHER"
/>
</intent-filter>
</activity>
</application>
</manifest>
Out Put:-
·
Intent:-
Intent
are used as a
message passing mechanism between
activity serves and
run-time environment application. Android for
provide intent class
to give the
facility of message
passing. An intent is
used to pass
same information the inter (between application) or intra(same
application) application.
There are two
type of intent:-
1- Explicit
Intent,
2- Implicit Intent.
1- Explicit Intent (within application):-
Explicit intent
are used to invoke
the activity are
perform same action
within the application . They have specified a component
which provides the exact class to be run. Object of
explicit intent are
created by the
specifying the class
name of an
activity service.
Example:-
File->> New->>
Android project->> Project
Name->> Explicit Intent->> Next ->> Select Build Target->> Android
2.3.3->> Next->> Package Name->> com.azeem.explicitIntent->> Finish
Click Explicit Intent file
name->> res->> layout->> main.xml
Main.xml
<?xml version="1.0"
encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<EditText android:id="@+id/editText1"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:text=""
android:hint="Enter Name">
</EditText>
<Button android:text="Button"
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></Button>
</LinearLayout>
Second.xml
<?xml version="1.0"
encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText android:text=""
android:id="@+id/txtEdit"
android:layout_width="fill_parent"
android:layout_height="wrap_content"></EditText>
<Button android:text="Button"
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></Button>
</LinearLayout>
Main.java:-
package com.tech.myPack;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import
android.view.View.OnClickListener;
import android.widget.Button; import android.widget.EditText;
import android.widget.Toast;
public class main extends Activity implements OnClickListener{
EditText txtEdit; Button
btnSubmit;
public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.main);
txtEdit=(EditText)findViewById(R.id.editText1);
btnSubmit=(Button)findViewById(R.id.button1); btnSubmit.setOnClickListener(this); }
public void onClick(View v) {
String
string=txtEdit.getText().toString(); Intent intent=new
Intent(this,second.class); intent.putExtra("msg",string); startActivity(intent); }}
Second.java:-
package com.tech.myPack;
import android.app.Activity;
import android.content.Intent; import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener; import android.widget.Button;
import android.widget.EditText;
public class second extends Activity{
EditText txtSecond;
protected void onCreate(Bundle
savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.second);
txtSecond=(EditText)findViewById(R.id.txtEdit);
Intent
intent=getIntent(); String
string=intent.getStringExtra("msg"); txtSecond.setText(string);
}}
AndroidManifest.xml
<?xml version="1.0"
encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tech.explicitIntent"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="10"
/>
<application android:icon="@drawable/icon"
android:label="@string/app_name">
<activity android:name=".main"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN"
/>
<category android:name="android.intent.category.LAUNCHER"
/>
</intent-filter>
</activity>
<activity android:name=".second"
/>
</application>
</manifest>
2-
Implicit
Intent ( between two application):-
Implicit intent
are used to
invoke the activity
for another application. These intent are
created by specific
the action (Action
is logical name
at an activity). The intent resolution mechanism
resolves around matching an intent against all of Intent Filter descriptions in
the installed application package.
Example:-
Intent xyz =new
Intent(android.intent.action.EDIT);
startActivity(xyz);
Example:-
File->> New->>
Android project->> Project
Name->> Implicit
Intent->> Next ->>
Select Build Target->> Android 2.3.3->> Next->>
Package Name->>
com.azeem.implicitIntent->>
Finish
Click Implicit Intent file
name->> res->> layout->> main.xml
Main.xml
<?xml version="1.0"
encoding="utf-8"?> <LinearLayout xmlns:android=http://schemas.android.com/apk/res/android
android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical"
>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="OpenBrowser"
android:onClick="OpenBrowser"/>
</LinearLayout>
Main.java:-
package com.tech.azeem;
import
android.app.Activity;
import android.content.Intent; import
android.net.Uri;
import
android.os.Bundle;
import android.view.View; import
android.view.View.OnClickListener;
import
android.widget.Button;
public class ImplicitIntentActivity extends Activity
implements OnClickListener { /** Called when the activity is first
created. */
Button OpenBrowser;
public void
onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); setContentView(R.layout.main);
Intent xyz=new Intent("android.intent.action.View",Uri.parse
("http://learningapplicationlanguages.blogspot.in"));
startActivity(xyz);
}
public void onClick(View v) { // TODO Auto-generated method stub finish(); } }
SQLite DataBase
Introdection to SQLite:-
· SQLite is a
tool provided by android framework. Library of this tool is written in C
i.e. we need not require any external RDBMS to store data of an android Apps.
· SQLite is an lightweight database tools which is
use in number
of hand hilt device like
i-port, Apple i-phone, and Android
Mobile Phone, etc.
· In SQLite database file is created with extension “.db”.
e.g. student .db
· This data base
file take less memory in device.
There are
four way’s storing the data
i- Preferences
(small data),
ii- File ,
iii-
SQL (storing large data),
iv-
Network
i-
Preferences (small data):-
Preferences are used to store user preferences for a single application or across
application in a mobile. They are typically name value pairs accessible to the
context.
ii-
File
:-
Files can be stored directly on to the mobile or to
extended storage mediums. They are by default not accessible to applications
other than the one that created it.
iii-
SQL
(RDBMS(storing large data)):-
Android support creation of database based on SQLite.
These are again private to the application that created it.
iv-
Network:-
Android provides API support to store data over the network on
to a server, probably.
SQLite Architecture:-
1- Packages
The package android.database contains all
general classes for working with
databases. android.database.sqlite contains the
SQLite specific classes.
2-SQLiteOpenHelper
SQLite
OpenHelper is an
abstract class provided
by android framework
to manage onCreate() and onUpgrade() methods.
onCreate() is
called by the
framework, if the
database does not exists.
public abstract void onCreate (SQLiteDatabase db)
onUpgrade() is
called, if the
database version is increased
in your application
code. This method allows you to update the database schema.
public abstract void onUpgrade (SQLiteDatabase db,
int oldVersion, int newVersion)
Both methods receive a SQLiteDatabase object
as parameter which represents
the database.
public SQLiteOpenHelper (Context context, String name, SQLiteDatabase.CursorFactory factory, int version)
Cursor:-
It’s a framework provided class that
provides utility methods for obtaining values from the database. Some commonly used
methods of cursor class are.
public boolean moveToFirst(); public boolean moveToLast (); public int count(); public String getString(int, index); Public Type getType (int, index);
CursorFactory:- It’s provide a refrains of the cursor implementation.
3-SQLiteDatabase
SQLiteDatabase
class is used to manage, represent the database & provides some operational
methods i.e. This class provides some
methods to represent operation which can be performed on the database.
public void execSQL (String sql);
public Cursor query ();
public Cursor insert();
public Cursor update();
public Cursor delete();
Method of SqliteDatabase
1-execlSql()- used to execute a
sql statement passing argument.
Syntex:- public void execSql(String SqlStatement);
2-query()- method is
used to fetch
record from database without passing any sql Statement.
Syntex:- Public
Cursor query(String
tableName, String[] coloums, String selection, String[] selectionArgs, String
groupBy, String having);
5-Content Providers
These are
used to share data
with other activities
or services(inter and intra application ). A content
provider uses a standard
interface in the
form of a URI
to fulfil requests
for data from
other applications that
may not even
know which content provider they
are using.
For Example:-
when an
application issues a
query for Contact data,
it addresses the
query to a URI
of the form:
content://contacts/people
In Android each application execute in a
separate Process i.e. resource and
data of one
application cannot be
directly access by
another application.
A content
provider is represented
by subclass of
content provider this
class provides some
method to perform
data base operation;-
onCreate():- is used
by Content Provider to
create data share.
quary():- is
used by Content Provider to
return all the data or
single record as a
courser.
i
nsert():- is used by Content
Provider to insert
record.
delete():- is used by Content Provider
delete().
update():- is used by Content Provider update().
UR (Uniform
Resources Identifier)I:-
.It’s stand
for “Uniform Resources
Identifier”. Itch
contain provider expose
a unique URI
that is used
by consumer to
interact with it.
Content://com.azeem.student/student
URI of a
CP has three parts-
1-
Each
URI start is content://
which represent a CP
at as
a protocol.
2-
Athority:- com.azeem.student
It is an uncials identified string
i.e. provider by
operation developer usually
package name is
used as an
authority.
3-
Path Segment:- /student
It’s a represent
type of data being
return or manage
by content provider
class student extend content Provider {
public static
Uri CONTENT_URI=uri.parse (“content://com.tech.student/student”);
}
Mine Type:-
It’s
helped to the runtime environment to
identified Content Provider. Each Content
Provider need to
space Min Type for
a single record. Mine Type has two part which is
separate by “/ ”
1:-Major part:-
(predefine(static))
vnd.android.cursor.dir
- major part of mine type for all
the records. vnd.android.cursor.item - major part of mine type
for a single record.
2-Minor part-(user define (Dynamic))
Minor part is an unequally
identifier string.
Content Resolvers:-
Each application
Context has a
single Content Resolver,
accessible using the getContentResolver method, as shown
in the following
code snippet:
ContentResolver cr =
getContentResolver();
Content Resolver includes several methods to
transact and query Content Providers. You specify the provider to interact using a URI.
6- Broadcast
Receivers
What are BroadcastReceivers
·
A Broadcast Receiver is an android application
component that is used to receive to broadcast intent. Normally broadcast is
used to perform background events such as battery low.
·
Time of Broadcast Receiver is very low i.e. max-5sec. If time
exceeds then broadcast will be killed by ARE and application
unresponsive dialog will be appear.
·
Usually broadcast perform short time operation which
has no interaction.
There are two major classes of broadcasts that can be received:
1- Normal
broadcasts:- (sent with Context.sendBroadcast)
are completely asynchronous. All receivers of the broadcast are run in an
undefined order, often at the same time. This is more efficient, but That Means
receivers cannot use the result or abort APIs included here.
2- Ordered broadcasts:-(sent with Context.sendOrderedBroadcast) are delivered to one
receiver at a time. As each receiver executes each in turn, it can propagate a
result to the next receiver, or it can completely abort the broadcast so That
it will not be passed to other receivers. The order receivers run in can be
controlled with the android: priority attribute of the matching intent-filter;
receivers with the same priority will be run in an arbitrary order.
To register a Broadcast Receiver
we have two mechanisms –
1- Broadcast Receiver is register by putting on
receiver element in android.manifest.xml
file as a sub element of <app> element.
<receiver android:name=“MyReceiver”> <intent-filter>
<action android=“com.azeem.MyBCIntent”> </intent-filter>
</receiver>
2- Broadcast Receiver can be register by invoking
registerReciver().
This method takes two parameters-
i - BroadCastReceiver object,
ii- Intent- filter.
i - Broadcast Receiver object:-
public
void registerReciver(BCR receiver, IntentFilter filter); MyReceiver
receiver=new MyReceiver (); IntentFilter filter=new
IntentFilter(“com.azeem.MyReceiver”); registerReceiver(receiver, filter);
ii- Intent- filter:-
·
An Intent-filter
specifies the types of Intent that an activity, service or Broadcast
Receiver can respond to. An
Intent-filter declares the capabilities of a component. It specifies what
an activity or service do and what types of broadcasts a receiver can handle.
·
Most intent-filters are declared in AndroidManifest.xml of an application.
AndroidManifest.xml
<activity
android:name=".Hello world" android:label="name">
<intent-filter>
<action
android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.DEFAULT"
/> </intent-filter> </activity>
Pending Intent:-
An application can create a Pending Intent, which is nothing but an intent and action to it, so that it can passed to some other applications which can execute this pending intent as if original application executes it.
An application can create a Pending Intent, which is nothing but an intent and action to it, so that it can passed to some other applications which can execute this pending intent as if original application executes it.
A Pending Intent is a token that
you give to another application (e.g. Notification Manager, Alarm Manager or
other 3rd party applications), which allows this other application to use the
permissions of your application to execute a predefined piece of code.
Pending Intents can be
created of three types
1- getActivity
(Context, int, Intent, int), 2- getBroadcast (Context, int, Intent,
int),
3- getService (Context, int, Intent, int);
3- getService (Context, int, Intent, int);
You
can create a pending intent to launch an activity or service, broadcast intent. Let us
see how to
create an pending
intent which can launch
an activity and
see once you
have pending Intent, how can
you launch make
operation on the intent.
Create a two activities in your android project.
Create a two activities in your android project.
1- One activity
create an pending Intent through 'getActivity()’api
PendingIntent pendingIntent;
Intent intent
= new Intent ();
intent.setClass
(Context, activity2. class);
pendingIntent
= PendingIntent. GetActivity (Context, 0, intent, 0);
2-
Pass activity-2 asset Class parameter to
intent and create the pending Intent.
In activty-1 , for button
click action, use
the pending Intent instance to
perform the operation
on it using 'send()‘api
.
Intent intent = new Intent();
try {
pendingIntent.send(mContext, 0, intent);
} catch (PendingIntent.CanceledException e) {
// the stack trace isn't very helpful here. Just log the exception message.
System.out.println ( "Sending contentIntent failed: " );
}
try {
pendingIntent.send(mContext, 0, intent);
} catch (PendingIntent.CanceledException e) {
// the stack trace isn't very helpful here. Just log the exception message.
System.out.println ( "Sending contentIntent failed: " );
}
Method of Broadcast Receiver:-
If
we register BCR
by register receiver
method then we
have to unregister
this receiver by
invoking, unRegisterReceiver();
telephony
Manager service is
used and event
broadcast to notified
other application about
difference change of
state.
Any
application which is
instructed in change
of state of
device need to
perform following operation-
(1). Broadcast Receiver is to
be define which
has and intent-filter for PHONE_STATE. PHONE_STATE is
a broadcast Application that
used to broadcast
change of stated
of a PHONE. In the
onReceiver()method of
broadcastReciver phoneStaticListener object is
to be create
and register with
the telephony Manager to
receive the notification of specific
change of state.
phoneStaticListener () is
a framework provide
a class which
provide the call
back method used
by telephonyManager() service
to notified the
change of state.
onCallStateChanged() of
phoneStaticListener() is to
over reading by application
developer to perform
the task when
incoming or outgoing
are receive.
7- Services
- Overview of services in
Android
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.
For example, a service
might handle network
transactions, play music, perform
file I/O, or
interact with a
content provider, all from
the background.
- Implementing a service
. A
service can essentially
take two forms:
1-Started (Local)Service:-
onStartCommand()
A service
is "started“ when
an application component (such as an activity)
starts it by
calling startService().
For Example:-
It might download
or upload a file over
the network. When the operation
is done, the
service should stop itself.
2-Bound (Remote)Service:-
onBind();
A service is
"bound“ when an
application component binds to it by calling
bindService(). A bound
service offers a client- server interface
that allows components
to interact with the
service, send requests,
get results, and even
do so across
processes with interposes.
A bound
service runs only
as long as
another application
component is bound
to it. Multiple components can
bind to the
service at once,
but when all of
them unbind, the service
is destroyed.
Declaring
a service in
the manifest Like activities (and other
components), you must
declare all services
in your application's manifest
file.
To declare
your service, add a <service> element as a
child of
the <application> element.
For Example:-
<manifest ... > ... <application ...
>
<service
android:name=".ExampleService" /> ... </application>
</manifest>
1-START_STICKY:-
If the
system kills he
service after onStartCommand() returns,
recreate the service
and call onStartCommand(), but do not redeliver the
last intent. Instead,
the system calls onStartCommand() with
a null intent,
unless there were
pending intents to
start the service,
in which case, those
intents are delivered.
This is suitable
for media players
(or similar services) that are
not executing commands,
but running indefinitely and
waiting for a
job.
2-START_REDELIVER_INTENT:-
If the
system kills the service after
onStartCommand() returns, recreate
the service and call onStartCommand() with the last intent
that was delivered
to the service. Any pending
intents are delivered
in turn. This is suitable
for services that
are actively performing
a job that should
be immediately resumed,
such as downloading a
file.
3-START_NOT_STICKY:-
If the
system kills the
service after onStartCommand()
returns, do not
recreate the service, unless there
are pending intents
to deliver. This is
the safest option
to avoid running
your service when not
necessary and when
your application can
simply restart any unfinished
jobs.






























No comments:
Post a Comment