Saturday, March 19, 2011

Services, BroadCast Reciever and Content Provider

1) What is Services ?
Answer :- A service doesn't have a visual user interface, but rather runs in the background for an indefinite period of time. For example, a service might play background music as the user attends to other matters, or it might fetch data over the network or calculate something.

2) What is Life Cycle of Services ?
Answer :- There are two ways to start a services.
Context.startService()   Context.bindService()


3) What is difference between Context.startService() and Context.bindService() ?
Answer :-
Context.startService() -> 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.
Context.bindService() -> 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.



4) What is Bound Services ?
Answer :- A bound service is the server in a client-server interface. A bound service allows components (such as activities) to bind to the service, send requests, receive responses, and even perform interprocess communication (IPC). A bound service typically lives only while it serves another application component and does not run in the background indefinitely.


5) What is BroadCast Reciever ?
Answer :- A broadcast receiver is a component that does nothing but receive and react to broadcast announcements. Many broadcasts originate in system code — for example, announcements that the timezone has changed, that the battery is low, that a picture has been taken, or that the user changed a language preference. All receivers extend the BroadcastReceiver base class. A BroadcastReceiver object is only valid for the duration of the call to onReceive(Context, Intent). Once your code returns from this function, the system considers the object to be finished and no longer active.

6) What is Content Provider ?
Answer :- Content providers store and retrieve data and make it accessible to all applications. They're the only way to share data across applications. For example, the contacts data is used by multiple applications and must be stored in a content provider. If you don't need to share data amongst multiple applications you can use a database directly via SQLiteDatabase.
Content Provider is achived by a ContentResolver interface. Requests to ContentResolver are automatically forwarded to the appropriate ContentProvider instance. The primary methods that need to be implemented are:

  • onCreate() which is called to initialize the provider
  • query(Uri, String[], String, String[], String) which returns data to the caller
  • insert(Uri, ContentValues) which inserts new data into the content provider
  • update(Uri, ContentValues, String, String[]) which updates existing data in the content provider
  • delete(Uri, String, String[]) which deletes data from the content provider
  • getType(Uri) which returns the MIME type of data in the content provider
Data access methods (such as insert(Uri, ContentValues) and update(Uri, ContentValues, String, String[])) may be called from many threads at once, and must be thread-safe. Other methods (such as onCreate()) are only called from the application main thread.

7) Give a small example of Content Provider ?
Answer :- 
In ContentUserDemo.java
package org.example.contprov;
import java.util.ArrayList;
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.Contacts.People;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class ContentUserDemo extends Activity {
private static final String TAG = "ContentUserDemo";
private ArrayList<String> list;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

// Get content provider and cursor
ContentResolver r = getContentResolver();
Cursor cursor = r.query(People.CONTENT_URI, null, null, null, null);

// Let activity manage the cursor
startManagingCursor(cursor);
Log.d(TAG, "cursor.getCount()=" + cursor.getCount());

// Get value from content provider
int nameIndex = cursor.getColumnIndexOrThrow(People.NAME);
int numberIndex = cursor.getColumnIndexOrThrow(People.NUMBER);

cursor.moveToFirst();
list = new ArrayList<String>();
do {
String name = cursor.getString(nameIndex);
String number = cursor.getString(numberIndex);
list.add(name + ": " + number);
} while (cursor.moveToNext());

// Get the list view
ListView listView = (ListView) findViewById(R.id.listView);
ArrayAdapter<String> aa = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
listView.setAdapter(aa);
}
}

In layout/main.xml :- This layout just dumps the data in a ListView. One interesting part is linking the ArrayAdapter to the ListView, in the previous file.
<?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">
<ListView android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/listView"></ListView>
</LinearLayout>

AndroidManifest.xml :- Don't forget to ask for permission to read the contacts from the system Content Provider.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.example.cp" android:versionCode="1" android:versionName="1.0.0">
<uses-permission android:name="android.permission.READ_CONTACTS" />
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".ContentUserDemo" android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

Results :- You should see the list of people from your Contacts printed in your own application.