Saturday, January 24, 2015

Android Implicit Intents

There are times that you want to utilize another application on the Android device for some action in your application. For example, let's say you have an application that opens a browser and navigate to a web site. You wouldn't want to build your own browser (most likely anyway), so you'd just let the Android device choose an application to use for navigating to the web site. When you do this, you're using an implicit intent. Here's how you do it.

private void navigateToWebSite() {
   // Create an intent for viewing a specific web site
   Uri google = Uri.parse("http://developer.android.com");
  
   Intent intent = new Intent(Intent.ACTION_VIEW, google);
  
   // Create a chooser intent
   Intent chooserIntent = Intent.createChooser(intent, "Browse with...");
        
   // Start the chooser activity
   if (intent.resolveActivity(getPackageManager()) != null) {
      startActivity(chooserIntent);
   }
}

The chooserIntent is optional. I'm using it to add a custom title to the chooser dialog. You can simply create the intent and call "startActivity(intent)" and let Android display the standard chooser dialog.

In this example, we just told Android to include any application that can handle the ACTION_VIEW intent. What if you have written your own application that you want to include as an option for handling  this type of intent? In your application's AndroidManifest.xml file, you simply add an intent-filter within the definition of the activity.

For example, here I've added a second intent-filter to handle any applications that initiates an intent on the Intent.ACTION_VIEW with "http" requests, just like in the example above.

<activity android:label="@string/app_name" android:name=".MyOtherActivity">

       <intent-filter>
           <action android:name="android.intent.action.MAIN" />

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

         <intent-filter>
             <action android:name="android.intent.action.VIEW">

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

             <data android:scheme="http">
         </intent-filter>

</activity>



No comments:

Post a Comment