67
Android App Development

Android app deveopment

Embed Size (px)

DESCRIPTION

 

Citation preview

Page 1: Android app deveopment

Android App Development

Page 2: Android app deveopment

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

Page 3: Android app deveopment

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

Page 4: Android app deveopment

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

Page 5: Android app deveopment

NotificationsThere are Basically three kinds of Notifications in android:

1. Toast Notification

2. StatusBar Notifications

3. Dialog Notifications

Page 6: Android app deveopment

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.

Page 7: Android app deveopment

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

Page 8: Android app deveopment

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|Gravity.LEFT, 0, 0);

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

Page 9: Android app deveopment

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).

Page 10: Android app deveopment

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);

Page 11: Android app deveopment

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);

Page 12: Android app deveopment

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

Page 13: Android app deveopment

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.

Page 14: Android app deveopment

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

Page 15: Android app deveopment

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();

Page 16: Android app deveopment

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();

Page 17: Android app deveopment

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);

Page 18: Android app deveopment

Custom DialogPlease Refer :

http://developer.android.com/guide/topics/ui/dialogs.html#AlertDialog

Page 19: Android app deveopment

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.

@Overrideprotected Dialog onCreateDialog(int id) { switch (id) { case DATE_DIALOG_ID: return new DatePickerDialog(this, mDateSetListener, mYear, mMonth,

mDay); } return null;}

Page 20: Android app deveopment

DatePickerDialog// the callback received when the user "sets" the date in the dialog– private DatePickerDialog.OnDateSetListener mDateSetListener

=– new DatePickerDialog.OnDateSetListener() {

– public void onDateSet(DatePicker view, int year, – int monthOfYear, int dayOfMonth) {– mYear = year;– mMonth = monthOfYear;– mDay = dayOfMonth;– updateDisplay();– }– };Reference :

http://developer.android.com/resources/tutorials/views/hello-datepicker.html

Page 21: Android app deveopment

Time Picker DialogPlease Refer: http://developer.android.com/resources/tutorials/views/hello-

timepicker.html

Page 22: Android app deveopment

End Of Notifications

Page 23: Android app deveopment

Debugging Android Application

Page 24: Android app deveopment

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.

Page 25: Android app deveopment

Debug Tools Adb Dalvik Debug Monitor Server Device or Android Virtual Device Heirarchy Viewer and layoutopt Traceview Dev Tools Android application

Page 26: Android app deveopment

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.

Page 27: Android app deveopment

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.

Page 28: Android app deveopment

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.

Page 29: Android app deveopment

Heirarchy Viewer and layoutopt

Graphical programs that let you debug and profile user interfaces.

Page 30: Android app deveopment

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.

Page 31: Android app deveopment

End of Debugging android application

Reference: http://developer.android.com/guide/developing/debugging/index.html

Page 32: Android app deveopment

Intent and intent filters

Page 33: Android app deveopment

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.

Page 34: Android app deveopment

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

Page 35: Android app deveopment

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

Page 36: Android app deveopment

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().

Page 37: Android app deveopment

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().

Page 38: Android app deveopment

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

Page 39: Android app deveopment

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.

Page 40: Android app deveopment

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

Page 41: Android app deveopment

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.

Page 42: Android app deveopment

Intent Filter Code snippetAction 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>

Page 43: Android app deveopment

Intent Filter Code snippetCategory test :

<intent-filter . . . > <category

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

android:name="android.intent.category.BROWSABLE" /> . . .</intent-filter>

Page 44: Android app deveopment

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>

Page 45: Android app deveopment

Intent Filter Code snippetCommon 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>

Page 46: Android app deveopment

End of Intent and Intent Filters

Page 47: Android app deveopment

2. Multimedia in android

Page 48: Android app deveopment

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

Page 49: Android app deveopment

Multimedia in android Please refer Following link to see the Media formats supported

by android:

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

Page 50: Android app deveopment

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)

Page 51: Android app deveopment

Simple Media PlayBackUsing 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)

Page 52: Android app deveopment

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

Page 53: Android app deveopment

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 hereMediaPlayer mediaPlayer = new MediaPlayer();mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC

);mediaPlayer.setDataSource(getApplicationContext(), myUri);mediaPlayer.prepare();mediaPlayer.start();

Page 54: Android app deveopment

Media Player code snippet

Play From URL external site :

String url = "http://........"; // your URL hereMediaPlayer mediaPlayer = new MediaPlayer();mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);mediaPlayer.setDataSource(url);mediaPlayer.prepare(); // might take long! (for buffering, etc)mediaPlayer.start();

Page 55: Android app deveopment

Media Player

More Info Please refer :http://developer.android.com/guide/topics/media/

mediaplayer.html

Page 56: Android app deveopment
Page 57: Android app deveopment

Supported video formats Please Refer This Link for supported vedio formats

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

Page 58: Android app deveopment

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

Page 59: Android app deveopment

SQLite Database

Page 60: Android app deveopment

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.

Page 61: Android app deveopment

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); }}

Page 62: Android app deveopment

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.

Page 63: Android app deveopment

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.

Page 64: Android app deveopment

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.

Page 65: Android app deveopment

Practical Approach and Good Practices

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

verview_sqlite

Page 66: Android app deveopment

Basic content providers

Page 67: Android app deveopment

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/1954http://www.devx.com/wireless/Article/43005/0/page/2