Tuesday, 18 December 2012

Intent Filter


Intent Filters are similar to putting Hooks (SetWindowHook) in windows.

1. Using this we can register for some actions (action can be default actions like battery charged,or invoking a URL or custom action strings).
2. Android will automatically invoke the activity associated that intent filter.

Intent filter is defined in the AndroidManifest.xml file.

Say we want to launch an activity when someone invokes a URL



<activity android:name="Downloader">
   <intent-filter>
      <action android:name = "android.intent.action.VIEW"/>
      <category android:name ="android.intent.category.DEFAULT"/>
      <data android:scheme = "http" />
     <data android:host= "www.google.com" />
    </intent-filter>
 </activity>

In this case our activity name is Downloader. Say it is for downloading the web page associated with URI.
Now if we invoke a URI like this android will automatically show a popup menu which contains the default Browser and our  Downloader activity.


Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("http://www.google.com"));
startActivity(intent);

But this will work only for "wwww.google.com" because we provided host name as "www.google.com". Remove that host name for launching our Downloader activity for any URL.

Now let us say we want to launch an activity, and it should be invoked for dialing number. That is for the scheme "tel:" , remember earlier our scheme (data android:scheme ) was "http". Android uses will use this scheme to identify the activities.  In this case intent filters for the CustomDialer activity can be registered like this.


<activity android:name=".CustomDialer">
   <intent-filter>
      <action android:name = "android.intent.action.CALL"/>
      <category android:name ="android.intent.category.DEFAULT"/>
      <data android:scheme = "tel" />
  </intent-filter>
</activity>


Now if someone calls dials a number like this

Intent intent = new Intent(Intent.ACTION_CALL,Uri.parse("tel:919494125066"));
android will show a popup menu containing default Dialer  and our CustomDialer activities.




No comments:

Post a Comment