Sei sulla pagina 1di 67

Android App Development

1.Notifying the users



Debugging android applications
Intent and intent filters

2.Multimedia in android

Multimedia supported audio formats
Simple media playback
Supported video formats

3.sql database

Introducing sqlite
Sqlite open helper and creating a database
Opening and closing a database

4.Basic content providers

Content provider mime types
Searching for content Adding, changing,
and removing content




5.Graphics and Animations

Drawing graphics in android
Drawing with xml
Canvas drawing best practice

6.Accessing android hardware

Using the media apis
Using the camera
Using the accelerometer and compass




1.Notifying the users

Debugging android applications
Intent and intent filters

2. Multimedia in android

Multimedia supported audio formats
Simple media playback
Supported video formats


Notifications
There are Basically three kinds of Notifications in android:

1. Toast Notification

2. StatusBar Notifications

3. Dialog Notifications



Notification : Toast
A toast notification is a message that pops up on the surface of the
window.

The notification automatically fades in and out, and does not accept
interaction events.

A toast is best for short text messages, such as "File saved," when
you're fairly certain the user is paying attention to the screen.


Toast: Code Snippet



Context context = getApplicationContext();

CharSequence text = "Hello toast!";

int duration = Toast.LENGTH_SHORT;

Toast toast = Toast.makeText( context , text , duration);

toast.show();

(OR)

Toast.makeText(context, text, duration).show();



Reference : http://developer.android.com/guide/topics/ui/notifiers/toasts.html
Positioning the Toast:

public void setGravity (int gravity, int xOffset,
int yOffset)


This Sets the location at which the notification
should appear on the screen.







toast.setGravity(Gravity.TOP|Gravi
ty.LEFT, 0, 0);









Reference :
http://developer.android.com/reference/android/
widget/Toast.html#setGravity%28int,%20int,%20
int%29
Status Bar Notification



A status bar notification adds an icon to the system's status bar
(with an optional ticker-text message) and an expanded message in
the "Notifications" window.

When the user selects the expanded message, Android fires an
Intent that is defined by the notification (usually to launch an Activity).


Status Bar Notification :
code snippet
Get a reference to the NotificationManager:

String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns);

Instantiate the Notification:

int icon = R.drawable.notification_icon;
CharSequence tickerText = "Hello";
long when = System.currentTimeMillis();

Notification notification = new Notification(icon, tickerText, when);


Status Bar Notification :
code snippet
Define the notification's message and PendingIntent:

Context context = getApplicationContext();
CharSequence contentTitle = "My notification";
CharSequence contentText = "Hello World!";
Intent notificationIntent = new Intent(this, MyClass.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle, contentText,
contentIntent);


Status Bar Notification :
code snippet
Pass the Notification to the NotificationManager:

private static final int HELLO_ID = 1;

mNotificationManager.notify(HELLO_ID, notification);




That's it. Your user has now been notified.


Reference :
http://developer.android.com/guide/topics/ui/notifiers/notifications.html
Dialog Notification
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 and short activities that
directly relate to the application in progress.
Dialog Notification:
Types
The Dialog class is the base class for creating dialogs. However, you
typically should not instantiate a Dialog directly. Instead, you should
use one of the following subclasses:

AlertDialog

ProgressDialog

DatePickerDialog

TimePickerDialog
Alert Dialog
A dialog that can manage zero, one, two, or three buttons, and/or a
list of selectable items that can include checkboxes or radio 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();
} })
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
Alert Dialog

final CharSequence[] items = {"Red", "Green", "Blue"};

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Pick a color");
builder.setSingleChoiceItems(items, -1, new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
Toast.makeText(getApplicationContext(), items[item],
Toast.LENGTH_SHORT).show();
}
});
AlertDialog alert = builder.create();
ProgressDialog
A ProgressDialog is an extension of the AlertDialog class that can
display a progress animation in the form of a spinning wheel, for a task
with progress that's undefined, or a progress bar, for a task that has a
defined progression.

ProgressDialog dialog = ProgressDialog.show(MyActivity.this, "",
"Loading. Please wait...", true);
Custom Dialog
Please Refer :

http://developer.android.com/guide/topics/ui/dialogs.html#AlertDialog
DatePickerDialog
To provide a widget for selecting a date, use the DatePicker widget,
which allows the user to select the month, day, and year, in a familiar
interface.



@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this, mDateSetListener,
mYear, mMonth, mDay);
}
return null;
}
DatePickerDialog
// the callback received when the
user "sets" the date in the dialog
private
DatePickerDialog.OnDateSetList
ener mDateSetListener =
new
DatePickerDialog.OnDateSetList
ener() {

public void
onDateSet(DatePicker view, int
year,
int
monthOfYear, int dayOfMonth) {
mYear = year;
mMonth =
monthOfYear;
mDay =
dayOfMonth;
updateDisplay();
}
};
Reference :
http://developer.android.com/resour
ces/tutorials/views/hello-
datepicker.html

Time Picker Dialog
Please Refer:
http://developer.android.com/resources/tutorials/views/hello-timepicker.html


End Of Notifications




Debugging Android
Application

Debugging Android
Application
The Android SDK provides most of the tools that you need to debug
your applications.

You need a JDWP-compliant debugger if you want to be able to do
things such as step through code, view variable values, and pause
execution of an application.

If you are using Eclipse, a JDWP-compliant debugger is already
included and there is no setup required.
Debug Tools

Adb

Dalvik Debug Monitor Server

Device or Android Virtual Device

Heirarchy Viewer and layoutopt

Traceview

Dev Tools Android application
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.
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 features.
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 the adb host daemon to communicate with the device or
emulator.
Heirarchy Viewer and
layoutopt


Graphical programs that let you debug and profile user interfaces.
Traceview


A graphical viewer that displays trace file data for method calls and
times saved by your application, which can help you profile the
performance of your application.
End of Debugging android
application
Reference:
http://developer.android.com/guide/developing/debugging/index.html


Intent and intent filters

Intent and Intent filters
Three of the core components of an application activities, services,
and broadcast receivers are activated through messages, called
intents.


Intent messaging is a facility for late run-time binding between
components in the same or different applications.

The intent itself, an Intent object, is a passive data structure holding
an abstract description of an operation to be performed or, often in
the case of broadcasts, a description of something that has happened
and is being announced.
Intent and Intent filters
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).


Component Name
Action
Data
Category
Extras
Flags

Component Name
The name of the component that should handle the intent.

This field is a ComponentName object a combination of the fully
qualified class name of the target component (for example
"com.example.project.app.FreneticActivity") and the package name set
in the manifest file of the application where the component resides (for
example, "com.example.project").

The package part of the component name and the package name set
in the manifest do not necessarily have to match.

Note :
The component name is optional. If it is set, the Intent object is
delivered to an instance of the designated class. If it is not set, Android
uses other information in the Intent object to locate a suitable target
Action
A string naming the action to be performed or, in the case of
broadcast intents, the action that took place and is being reported. The
Intent class defines a number of action constants, including these:
The action in an Intent object is set by the setAction() method
and read by getAction().
Data
The URI of the data to be acted on and the MIME type of that data.
Different actions are paired with different kinds of data specifications.

For example, if the action field is ACTION_EDIT, the data field
would contain the URI of the document to be displayed for editing.

If the action is ACTION_CALL, the data field would be a tel: URI
with the number to call.

Similarly, if the action is ACTION_VIEW and the data field is an http:
URI, the receiving activity would be called upon to download and
display whatever data the URI refers to.
The setData() method specifies data only as a URI, setType()
specifies it only as a MIME type, and setDataAndType() specifies it as
both a URI and a MIME type. The URI is read by getData() and the
type by getType().
Category


A string containing additional information about the kind of
component that should handle the intent. Any number of category
descriptions can be placed in an Intent object.


The addCategory() method places a category in an Intent object,
removeCategory() deletes a category previously added, and
getCategories() gets the set of all categories currently in the object.

Example : CATEGORY_BROWSABLE, CATEGORY_GADGET ,
CATEGORY_HOME , CATEGORY_LAUNCHER ,
CATEGORY_PREFERENCE
Extras
Key-value pairs for additional information that should be delivered to
the component handling the intent.

The Intent object has a series of put...() methods for inserting
various types of extra data and a similar set of get...() methods for
reading the data.

These methods parallel those for Bundle objects. In fact, the extras
can be installed and read as a Bundle using the putExtras() and
getExtras() methods.
Flags
Flags of various sorts. Many instruct the Android system how to
launch an activity (for example, which task the activity should belong
to) and how to treat it after it's launched (for example, whether it
belongs in the list of recent activities).

All these flags are defined in the Intent class.



References :

http://developer.android.com/guide/appendix/g-app-intents.html

http://developer.android.com/guide/topics/intents/intents-filters.html

Intent Resolution
Intents can be divided into two groups:

Explicit intents designate the target component by its name (the
component name field, mentioned earlier, has a value set). Since
component names 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.

Implicit intents do not name a target (the field for the component
name is blank). Implicit intents are often used to activate components
in other applications.

Intent Filter Code snippet
Action Test:

<intent-filter . . . >

<action android:name="com.example.project.SHOW_CURRENT" />
<action android:name="com.example.project.SHOW_RECENT" />
<action android:name="com.example.project.SHOW_PENDING" />
. . .
</intent-filter>
Intent Filter Code snippet
Category test :

<intent-filter . . . >
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
. . .
</intent-filter>
Intent Filter Code snippet
Data test :


<intent-filter . . . >
<data android:mimeType="video/mpeg" android:scheme="http" . . . />
<data android:mimeType="audio/mpeg" android:scheme="http" . . . />
. . .
</intent-filter>
Intent Filter Code snippet
Common cases :

<data android:mimeType="image/*" />

<data android:scheme="http" android:type="video/*" />

<intent-filter . . . >
<action android:name="code android.intent.action.MAIN" />
<category android:name="code android.intent.category.LAUNCHER" />
</intent-filter>



End of Intent and
Intent Filters





2. Multimedia in android

Multimedia in android
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.

Reference : http://developer.android.com/guide/topics/media/index.html

Multimedia in android

Please refer Following link to see the Media formats supported by
android:


http://developer.android.com/guide/appendix/media-formats.html

Multimedia supported Audio
formats

Audio Formats :

AAC LC/LTP
HE-AACv1 (AAC+)
HE-AACv2 (enhanced AAC+)
AMR-NB (.3GP)
AMR-WB (.3GP)
FLAC (Android 3.1 +)
MP3 (.mp3)
MIDI
Vorbis (.ogg ) (.mkv android 4.0+)
PCM/WAVE (.wav)

Simple Media PlayBack
Using Media Player:

One of the most important components of the media framework is
the MediaPlayer class. An object of this class can fetch, decode, and
play both audio and video with minimal setup. It supports several
different media sources such as:

1. Local resources
2. Internal URIs, such as one you might obtain from a
Content Resolver
3. External URLs (streaming)

Media Player code snippet

From Local file in raw folder : res/raw


MediaPlayer mediaPlayer = MediaPlayer.create(context,
R.raw.sound_file_1);
mediaPlayer.start();

// no need to call prepare(); create() does that for you
Media Player code snippet

Play from a URI available locally in the system (that you obtained through
a Content Resolver, for instance):



Uri myUri = ....; // initialize Uri here
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(getApplicationContext(), myUri);
mediaPlayer.prepare();
mediaPlayer.start();
Media Player code snippet

Play From URL external site :


String url = "http://........"; // your URL here
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(url);
mediaPlayer.prepare(); // might take long! (for buffering, etc)
mediaPlayer.start();
Media Player
More Info Please refer :
http://developer.android.com/guide/topics/media/mediaplayer.html



Supported video formats

Please Refer This Link for supported vedio formats

http://developer.android.com/guide/appendix/media-formats.html


3.Sql database

Introducing sqlite
Sqlite open helper and creating a database
Opening and closing a database

4.Basic content providers

Content provider mime types
Searching for content Adding, changing, and
removing content


SQLite Database

Introducing Sqlite Database
Store structured data in a private database

Android provides full support for SQLite databases. Any databases
you create will be accessible by name to any class in the application,
but not outside the application.

The recommended method to create a new SQLite database is to
create a subclass of SQLiteOpenHelper and override the onCreate()
method, in which you can execute a SQLite command to create tables
in the database.
Introducing Sqlite Database
public class DictionaryOpenHelper extends SQLiteOpenHelper {

private static final int DATABASE_VERSION = 2;
private static final String DICTIONARY_TABLE_NAME = "dictionary";
private static final String DICTIONARY_TABLE_CREATE =
"CREATE TABLE " + DICTIONARY_TABLE_NAME + " (" +
KEY_WORD + " TEXT, " +
KEY_DEFINITION + " TEXT);";

DictionaryOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DICTIONARY_TABLE_CREATE);
}
}
Introducing Sqlite Database
You can then get an instance of your SQLiteOpenHelper
implementation using the constructor you've defined. To write to and
read from the database, call getWritableDatabase() and
getReadableDatabase(), respectively.

These both return a SQLiteDatabase object that represents the
database and provides methods for SQLite operations.
Introducing Sqlite Database
You can execute SQLite queries using the SQLiteDatabase query()
methods, which accept various query parameters, such as the table to
query, the projection, selection, columns, grouping, and others.

For complex queries, such as those that require column aliases, you
should use SQLiteQueryBuilder, which provides several convienent
methods for building queries.

Every SQLite query will return a Cursor that points to all the rows
found by the query. The Cursor is always the mechanism with which
you can navigate results from a database query and read rows and
columns.
Introducing Sqlite Database
Note :

Android does not impose any limitations beyond the standard
SQLite concepts. It is recommend including an autoincrement value
key field that can be used as a unique ID to quickly find a record.

This is not required for private data, but if you implement a content
provider, you must include a unique ID using the BaseColumns._ID
constant.


Practical Approach and
Good Practices

Reference :
http://www.vogella.de/articles/AndroidSQLite/article.html#overview_s
qlite


Basic content providers


5.Graphics and Animations

Drawing graphics in android
Drawing with xml
Canvas drawing best practice

6.Accessing android hardware

Using the media apis
Using the camera
Using the accelerometer and compass
http://www.devx.com/wireless/article/42482/1954
http://www.devx.com/wireless/Article/43005/0/page/2

Potrebbero piacerti anche