Codes

Toast:
Toast.makeText(getApplicationContext(), ((TextView) view).getText(),Toast.LENGTH_SHORT).show();
------------------------
Intents:
Intent intent = new Intent(MyActivity.this, MyOtherActivity.class);
startActivity(intent);
------------------------

Service

Most confusion about the Service class actually revolves around what it is not:

-A Service is not a separate process. The Service object itself does not imply it is running in its own process; unless otherwise specified, it runs in the same process as the application it is part of.
-A Service is not a thread. It is not a means itself to do work off of the main thread (to avoid Application Not Responding errors).

Thus a Service itself is actually very simple, providing two main features:
A facility for the application to tell the system about something it wants to be doing in the background (even when the user is not directly interacting with the application). This corresponds to calls to Context.startService(), which ask the system to schedule work for the service, to be run until the service or someone else explicitly stop it.
A facility for an application to expose some of its functionality to other applications. This corresponds to calls to Context.bindService(), which allows a long-standing connection to be made to the service in order to interact with it.

When a Service component is actually created, for either of these reasons, all that the system actually does is instantiate the component and call its onCreate() and any other appropriate callbacks on the main thread. It is up to the Service to implement these with the appropriate behavior, such as creating a secondary thread in which it does its work.

Service Lifecycle :
There are two reasons that a service can be run by the system.

If someone calls Context.startService() then the system will retrieve the service (creating it and calling its onCreate() method if needed) and then call its onStartCommand(Intent, int, int) method with the arguments supplied by the client. The service will at this point continue running until Context.stopService() or stopSelf() is called. Note that multiple calls to Context.startService() do not nest (though they do result in multiple corresponding calls to onStartCommand()), so no matter how many times it is started a service will be stopped once Context.stopService() or stopSelf() is called; however, services can use their stopSelf(int) method to ensure the service is not stopped until started intents have been processed.

For started services, there are two additional major modes of operation they can decide to run in, depending on the value they return from onStartCommand(): START_STICKY is used for services that are explicitly started and stopped as needed, while START_NOT_STICKY or START_REDELIVER_INTENT are used for services that should only remain running while processing any commands sent to them. See the linked documentation for more detail on the semantics.

Clients can also use Context.bindService() to obtain a persistent connection to a service. This likewise creates the service if it is not already running (calling onCreate() while doing so), but does not call onStartCommand(). The client will receive the IBinder object that the service returns from its onBind(Intent) method, allowing the client to then make calls back to the service. The service will remain running as long as the connection is established (whether or not the client retains a reference on the service's IBinder). Usually the IBinder returned is for a complex interface that has been written in aidl. A service can be both started and have connections bound to it. In such a case, the system will keep the service running as long as either it is started or there are one or more connections to it with the Context.BIND_AUTO_CREATE flag. Once neither of these situations hold, the service's onDestroy() method is called and the service is effectively terminated. All cleanup (stopping threads, unregistering receivers) should be complete upon returning from onDestroy().

Audio and Video

Android includes a comprehensive Media Player to simplify the playback of audio and video.

Multimedia playback in Android is handled by the MediaPlayer class. You can play media stored in application resources, local files, Content Providers, or streamed from a network URL. In each case,
the file format and type of multimedia being played is abstracted from you as a developer.

The Media Player’s management of audio and video files and streams is handled as a state machine. In the most simplistic terms, transitions through the state machine can be described as follows:
- Initialize the Media Player with media to play.
- Prepare the Media Player for playback.
- Start the playback
- Pause or stop the playback prior to its completing.
- Playback complete.

To play a media resource you need to create a new MediaPlayer instance, initialize it with a media
source, and prepare it for playback.

Initializing Audio Content for PlaybackTo play back audio content using the Media Player, you need to create a new Media Player object and set the data source of the audio in question.

To play back audio using the Media Player, you can use the static create method, passing in the application Context and one of the following:
- A resource identifier
- A URI to a local file using the file:// schema
- A URI to an online audio resource as a URL
- A URI to a local Content Provider row

Initializing audio content for playback
Context appContext = getApplicationContext();
MediaPlayer resourcePlayer = MediaPlayer.create(appContext,R.raw.my_audio);
MediaPlayer filePlayer = MediaPlayer.create(appContext,Uri.parse("file:///sdcard/localfile.mp3"));
MediaPlayer urlPlayer = MediaPlayer.create(appContext,Uri.parse("http://site.com/audio/audio.mp3"));
MediaPlayer contentPlayer = MediaPlayer.create(appContext,Settings.System.DEFAULT_RINGTONE_URI);

Alternatively, you can use the setDataSource method on an existing Media Player instance. This method accepts a file path, Content Provider URI, streaming media URL path, or File Descriptor.

When using the setDataSource method it is vital that you call prepare on the Media Player before you
begin playback.

Using setDataSource and prepare to initialize audio playback
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource("/sdcard/test.3gp");
mediaPlayer.prepare();

In each case, once you’ve finished playback, callrelease on your Media Player object to free the associated resources:
mediaPlayer.release();

Android supports a limited number of simultaneous Media Player objects; not releasing them can cause runtime exceptions when the system runs out of resources.

Preparing for Video Playback
Playback of video content is slightly more involved than audio. To show a video, you must specify a display surface on which to show it. The following sections describe two alternatives for the playback of video content.

The first, using the Video View control, encapsulates the creation of a display surface and allocation and preparation of video content within a Media Player. The second technique allows you to specify your own display surface and manipulate the underlying Media Player instance directly.

Playing Video Using the Video ViewThe simplest way to play back video is to use the VideoView control. The Video View includes a Surface on which the video is displayed and encapsulates and manages a Media Player to manage the video playback.

The Video View supports the playback of local or streaming video as supported by the Media Player
component. Video Views conveniently encapsulate the initialization of the Media Player. To assign a video to play simply call setVideoPath or setVideoUri to specify the path to a local file, or the URI of a ContentProvider or remote video stream:
streamingVideoView.setVideoUri("http://www.mysite.com/videos/myvideo.3gp");
localVideoView.setVideoPath("/sdcard/test2.3gp");

Once initialized, you can control playback using the start, stopPlayback, pause, and seekTo methods. The Video View also includes the setKeepScreenOn method to apply a screen Wake Lock that will prevent the screen from being dimmed while playback is in progress.

Video playback using a Video View
VideoView videoView = (VideoView)findViewById(R.id.surface);
videoView.setKeepScreenOn(true);
videoView.setVideoPath("/sdcard/test2.3gp");
if (videoView.canSeekForward())
videoView.seekTo(videoView.getDuration()/2);
videoView.start();
[ . . . do something . . . ]
videoView.stopPlayback();
 
Setting up a Surface for Video Playback
The first step to using the Media Player to view video content is to prepare a Surface onto which the
video will be displayed. TheMedia Player requires a SurfaceHolder object for displaying video content,
assigned using the setDisplay method.


Sample layout including a Surface View
<?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">
<SurfaceView
android:id="@+id/surface"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center">
</SurfaceView>
</LinearLayout>
 

The Surface View is a wrapper around the Surface Holder object, which in turn is a wrapper around the Surface that is used to support visual updates from background threads.

Surface Holders are created asynchronously, so you must wait until the surfaceCreated handler has been fired before assigning the returned Surface Holder object to the Media Player.

Initializing and assigning a Surface View to a Media Player
public class MyActivity extends Activity implements SurfaceHolder.Callback
{
private MediaPlayer mediaPlayer;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mediaPlayer = new MediaPlayer();
SurfaceView surface = (SurfaceView)findViewById(R.id.surface);
SurfaceHolder holder = surface.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
holder.setFixedSize(400, 300);
}
public void surfaceCreated(SurfaceHolder holder) {
try {
mediaPlayer.setDisplay(holder);
} catch (IllegalArgumentException e) {
Log.d("MEDIA_PLAYER", e.getMessage());

} catch (IllegalStateException e) {
Log.d("MEDIA_PLAYER", e.getMessage());
} catch (IOException e) {
Log.d("MEDIA_PLAYER", e.getMessage());
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
mediaPlayer.release();
}
public void surfaceChanged(SurfaceHolder holder,
int format, int width, int height) { }
}



Initializing Video Content for Playback
Once you have created and assigned the Surface Holder to your Media Player, use the setDataSource method to specify the path, URL, or Content Provider URI of the video resource to play.

As with audio playback, if you’re passing a URL to an online media file, the file must be capable of
progressive download using the RTSP or HTTP protocols.

Once you’ve selected your media source, callprepare to initialize the Media Player in preparation for
playback.

Initializing video for playback using the Media Player
public void surfaceCreated(SurfaceHolder holder) {
try {
mediaPlayer.setDisplay(holder);
mediaPlayer.setDataSource("/sdcard/test2.3gp");
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IllegalArgumentException e) {
Log.d("MEDIA_PLAYER", e.getMessage());
} catch (IllegalStateException e) {
Log.d("MEDIA_PLAYER", e.getMessage());
} catch (IOException e) {
Log.d("MEDIA_PLAYER", e.getMessage());
}
}

Notification

Your applications can use Notifications to alert users without using an Activity. Notifications are handled by the Notification Manager, and currently have the ability to:
- Create new status bar icons
- Display additional information (and launch an Intent) in the extended status bar window
- Flash the lights/LEDs
- Vibrate the phone
- Sound audible alerts (ringtones, Media Store audio)


Using Notifications is the preferred way for invisible application components (Broadcast Receivers, Services, and inactive Activities) to alert users that events have occurred that may require attention. They are also used to indicate ongoing background Services — particularly Services that have been
set to foreground priority.

As a user interface metaphor, Notifications are particularly well suited to mobile devices. It’s likely that your users will have their phones with them at all times but quite unlikely that they will be paying attention to them, or your application, at any given time. Generally users will have several applications open in the background, and they won’t be paying attention to any of them.

In this environment it’s important that your applications be able to alert users when specific events occur that require their attention. Notifications can be persisted through insistent repetition, being marked ongoing, or simply by displaying an icon on the status bar. Status bar icons can be updated regularly or expanded to show additional information using the expanded status bar window

Permissions

Permissions are an application-level security mechanism that lets you restrict access to application components. Permissions are used to prevent malicious applications from corrupting data, gaining access to sensitive information, or making excessive (or unauthorized) use of hardware resources or external communication channels.

The native permission strings used by native Android Activities and Services can be found as static constants in the android.Manifest.permission class. To use permission-protected components, you need to add <uses-permission> tags to application manifests, specifying the permission string that each application requires.

When an application package is installed, the permissions requested in its manifest are analyzed and granted (or denied) by checks with trusted authorities and user feedback.

Declaring and Enforcing Permissions:
 <uses-permission
        android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission
        android:name="android.permission.USE_CREDENTIALS" />
    <uses-permission
        android:name="android.permission.MANAGE_ACCOUNTS" />
    <uses-permission
        android:name="android.permission.AUTHENTICATE_ACCOUNTS" />
    <uses-permission
        android:name="android.permission.INTERNET" />
    <uses-permission
        android:name="android.permission.WRITE_SETTINGS" />
    <uses-permission
        android:name="android.permission.WRITE_SECURE_SETTINGS" />
    <uses-permission
        android:name="android.permission.READ_CONTACTS" />
    <uses-permission
        android:name="android.permission.WRITE_CONTACTS" />
    <uses-permission
        android:name="android.permission.READ_SYNC_STATS" />
    <uses-permission
        android:name="android.permission.READ_SYNC_SETTINGS" />
    <uses-permission
        android:name="android.permission.WRITE_SYNC_SETTINGS" />


To include permission requirements for your own application components, use the permission attribute in the application manifest. Permission constraints can be enforced throughout your application, most usefully at application interface boundaries, for example:- Activities Add a permission to limit the ability of other applications to launch an Activity.
- Broadcast Receivers Control which applications can send broadcast Intents to your Receiver.
- Content Providers Limit read access and write operations on Content Providers.
- Services Limit the ability of other applications to start, or bind to, a Service.

In each case, you can add a permission attribute to the application component in the manifest, specifying a required permission string to access each component

Content Providers let you set readPermission and writePermission attributes to offer a more granular
control over read/write access.

Android Database

SQLite offers a powerful SQL database library that provides a robust persistence layer over which you have total control. Using SQLite you can create independent relational databases for your applications. Use them to store and manage complex, structured application data. Android databases are stored in the /data/data/<package_name>/databases folder on your device (or emulator). By default all databases are private, accessible only by the application that created them.

Content Providers offer a generic interface to any data source by decoupling the data storage layer from the application layer. Content Providers offer a standard interface your applications can use to share data with and consume data from other applications— including many of the native data stores.

SQLite is a well regarded relational database management system (RDBMS). It is Open-source, Standards-compliant, Lightweight & Single-tier.

CURSORS AND CONTENT VALUES:ContentValues are used to insert new rows into tables. Each Content Values object represents a single
table row as a map of column names to values.

Queries in Android are returned as Cursor objects. Rather than extracting and returning a copy of the result values, Cursors are pointers to the result set within the underlying data. Cursors provide a managed way of controlling your position (row) in the result set of a database query.
The Cursor class includes a number of navigation functions including, but not limited to, the following:
➤ 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
➤ getPosition Returns the current Cursor position

Android provides a convenient mechanism for simplifying the management of Cursors within your Activities. The startManagingCursor method integrates the Cursor’s lifetime into the calling Activity’s. When you’ve finished with the Cursor, call stopManagingCursor to do just that.

Querying a Database
To execute a query on a database use the query method, passing in:
- An optional Boolean that specifies if the result set should contain only unique values.
- The name of the table to query.
- A projection, as an array of strings, that lists the columns to include in the result set.
- A ‘‘where’’ clause that defines the rows to be returned. You can include ? wildcards that will
be replaced by the values passed in through the selection argument parameter.
- An array of selection argument strings that will replace the ?’s in the where clause.
- A ‘‘group by’’ clause that defines how the resulting rows will be grouped.
- A ‘‘having’’ filter that defines which row groups to include if you specified a group by clause.
- A string that describes the order of the returned rows.
- An optional string that defines a limit for the number of returned rows.

// Return all rows for columns one and three, no duplicates
String[] result_columns = new String[] {KEY_ID, KEY_COL1, KEY_COL3};
Cursor allRows = myDatabase.query(true, DATABASE_TABLE, result_columns,
null, null, null, null, null, null);
// Return all columns for rows where column 3 equals a set value
// and the rows are ordered by column 5.
String where = KEY_COL3 + "=" + requiredValue;
String order = KEY_COL5;
Cursor myResult = myDatabase.query(DATABASE_TABLE, null, where,
null, null, null, order);

Extracting values from a Cursor
int GOLD_HOARDED_COLUMN = 2;
Cursor myGold = myDatabase.query("GoldHoards", null, null, null, null, null, null);
float totalHoard = 0f;

// Make sure there is at least one row.
if (myGold.moveToFirst()) {
// Iterate over each cursor.
do {
float hoard = myGold.getFloat(GOLD_HOARDED_COLUMN);
totalHoard += hoard;
} while(myGold.moveToNext());
}
float averageHoard = totalHoard / myGold.getCount();

Because SQLite database columns are loosely typed, you can cast individual values into valid types as
required.

SAVING AND LOADING FILES

It’s good practice to use Shared Preferences or a database to store your application data, but there are still times when you’ll want to use files directly rather than rely on Android’s managed mechanisms. As well as the standard Java I/O classes and methods, Android offers openFileInput and openFileOuput to simplify reading and writing streams from and to local files.

Saving and loading files
String FILE_NAME = "tempfile.tmp";
// Create a new output file stream that’s private to this application.
FileOutputStream fos = openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
// Create a new file input stream.
FileInputStream fis = openFileInput(FILE_NAME);

These methods support only those files in the current application folder; specifying path separators will cause an exception to be thrown. If the file name you specify when creating a FileOutputStream does  not exist, Android will create it for you.

INCLUDING STATIC FILES AS RESOURCES
If your application requires external file resources, you can include them in your distribution package by placing them in the res/raw folder of your project hierarchy.

To access these read-only file resources, call the openRawResource method from your application’s Resource object to receive an InputStream based on the specified file. Pass in the file name (without extension) as the variable name from the R.raw class, as shown in the following skeleton code:

Resources myResources = getResources();
InputStream myFile = myResources.openRawResource(R.raw.myfilename);

Adding raw files to your resources hierarchy is an excellent alternative for large, preexisting data sources (such as dictionaries) for which it’s not desirable (or even possible) to convert them into Android databases.

Android’s resource mechanism lets you specify alternative resource files for different languages, locations, and hardware configurations. You could, for example, create an application that loads a different dictionary resource based on the user’s language settings.

FILE MANAGEMENT TOOLS
Android supplies some basic file management tools to help you deal with the file system. Many of these utilities are located within the standard java.io.File package.

➤ deleteFile Enables you to remove files created by the current application.
➤ fileList Returns a string array that includes all the files created by the current application.

These methods are particularly useful for cleaning up temporary files left behind if your application
crashes or is killed unexpectedly.