Friday 13 April 2012

Intent filters for #android beginners

Much have been written and discussed about Intent filters and their types (explicit and implicit). I am just going to discuss their usage in basic/simple android applications.
 
You don't need to define any intent-filter (other that the launcher activity) if your application doesn't call external intents e.g reading contacts, and you are not intended to receive any broadcast from other applications e.g receiving incoming call notification.

You should call your all activities and services with explicit intents i.e calling them with their names. For example if you have two activites and a service named:

1-FirstActiviy.java [launcher activity]
2-SecondActivity.java
3-MyService.java

your AndroidManifest.xml should look like this:

?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="sohail.aziz"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="9" />


    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >

        <activity
            android:name=".FirstActivity"
            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=".SecondActivity"
            android:label="@string/app_name" >
        </activity>
        <service android:name=".MyService" >
        </service>
</application>
</manifest>

To start service/activity you should use explicit intent like this

Intent i=new Intent(this,SecondActivity.class)
startActivity(i);

Intent ii=new Intent(this,Myservice.class);
startService(ii);

Do you have anything to tell? tell me.

No comments:

Post a Comment