Android Intents For App Integration (Call a Calculator, Play Video, Open an Editor)

androidpuzzleguyOne of the wonderful things about the Android platform is that it was designed to allow app developers to take advantage of the work of other app developers that precede them.  Android’s system of Intent messaging not only allows for application integration, it encourages it.

If your application needs to play music or video, you could use the Android SDK’s APIs to build that functionality directly in your application.  Or you could simply message another application which is probably already on the device to do the job for you.  If your application works with a lot of numbers and users would find it convenient to popup a calculator on occasion, you could write your own calculator app or you could simply message to open the calculator app that is already on the device.  Need a way to edit a simple text file?  Build your own app editor or message to open a text editor.  Need to view a PDF?  Yep – you can build your own PDF viewing Activity, or you could message to open a PDF viewer from within your application.

Why build it, when you can simply use the functionality already provided by other apps on the device?  That’s part of the premise behind intent messaging.

Intent Messaging

For more details on how to create and use intent messages, I’ll point you to a couple of wonderful resources to get you started.  First, go to Lars Vogel’s tutorial on intents here: http://www.vogella.com/articles/AndroidIntent/article.html. This tutorial gives you a great introduction to intents and intent filters.  It provides a number of example bits of code to get you started.  Next, run through the API guide (http://developer.android.com/guide/components/intents-filters.html) provided via the Android Developers site.  This guide is very detailed and provides all the in’s and out’s of creating and using intents and intent filters.

Examples of App Integration

With an understanding of intent messaging, I’ve provided four practical examples below of  how to leverage intents to integrate your app with other apps to handle common tasks.

Launch a Calculator

Most devices already come with stock calculator apps.  Most of these calculator apps have been built with a predefined intent filter.  Therefore, calling to have a calculator app opened from within your application is as simple as launching a calculator intent.  Here is the code to create a calculator intent and call to start the calculator activity.

   1: // activity name and package for stock calculator
   2: private static final String CALCULATOR_PACKAGE_NAME = "com.android.calculator2";
   3: private static final String CALCULATOR_CLASS_NAME = "com.android.calculator2.Calculator";
   4:  
   5: public void launchCalculator() {
   6:  
   7:     Intent intent = new Intent();
   8:     intent.setAction(Intent.ACTION_MAIN);
   9:     intent.addCategory(Intent.CATEGORY_LAUNCHER);
  10:     intent.setComponent(new Component Name(CALCULATOR_PACKAGE_NAME,
  11:             CALCULATOR_CLASS_NAME));
  12:     try {
  13:         this.start Activity(intent);
  14:     } catch (ActivityNotFoundException noSuchActivity) {
  15:         // handle exception where calculator intent filter is not registered
  16:     }
  17: }

image

You’ll note that the try/catch block should handle cases where a calculator is not provided on the device.  Device manufactures do differ and the types of stock applications they provide with their devices are not always the same.  Furthermore, a user could always choose to remove stock applications like the calculator.

Also, some vendors choose to define their own applications.  These applications may not conform to the standard application intents and intent filters.  For example, for a Samsung tablet device (Galaxy Tab 2) that I am currently working with, the calculator app uses a different package and class name.  The code below replaces lines 2 & 3 above to launch the calculator on recent Samsung devices like the Galaxy tablets.

   1: // for Samsung devices, here are calculator names/packages
   2: public static final String CALCULATOR_PACKAGE_NAME = "com.sec.android.app.popupcalculator";
   3: public static final String CALCULATOR_CLASS_NAME = "com.sec.android.app.popupcalculator.Calculator";
   4: private static MainMenuController instance = null;

Therefore, you may find you have to do a little research and add conditional code for some devices that you want to support.

Select and Play Audio

At Intertech, we built an app that allows users to find YouTube videos that match their favorite tunes from their device’s own music libraries.  The application is called Vid-iT and you can find it here.

select-musicsavefavs

In building this application, we saw no need to build our own music or video playing software.  The purpose of our app was to allow device users to attach their favorite music related videos to their favorite music – not to be the best music or video playing app.  The playing task is already provided by dozens of great applications.  Therefore, we chose to use intents to message these fine apps to do the work for us.  In fact, in this case, we also used intents to get back information about the music or video selected in these apps.  The bit of Android code to accomplish the launch of a music player to allow a user to select a song is displayed below.

   1: // Starts user's choice of music player for song selection.
   2: public void launchMusicPlayer(View view) {
   3:     Intent intent = new Intent();
   4:     intent.setAction(android.content.Intent.ACTION_GET_CONTENT);
   5:     intent.setDataAndType(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
   6:             AUDIO_MIME_TYPE);
   7:     startActivityForResult(intent, FIND_SONG_INTENT);
   8: }

In cases where several apps are registered with the same intent filter, Android assists the user in prompting them to pick the app they feel best meets the requirement.  Playing music and picking a song is a case in point.  There are often many applications on the device that can satisfy this need.  Android negotiates the appropriate selection of an app when multiple apps are registered (via intent filter) for the same intent.  As you can see in the picture below, Android allows the user to pick from all their installed music apps which app to use to play and pick the song for Vid-iT.

image

In this case, the music player allows a user to play and, importantly, select a particular music file.  From there, Vid-iT must find and associate appropriate videos.  So how do you get the music selection back from the music playing app?  Note from the code above that the music playing video was launched with a startActivityForResult( ) method.   The “ForResult” allows your app to get response back from the launched app.  In this case, the music app returns a music URI (a String references to one of the music songs in the music library) via the onActivityResult( ) method.  The music URI is tucked into the Intent message’s data section and is used by our app to now find videos.  The code for handling the return response is below.

   1: // called after returning from music selection app or playing music app
   2: protected void onActivityResult(int requestCode, int resultCode, Intent data) {
   3:     super.onActivityResult(requestCode, resultCode, data);
   4:     if ((requestCode == FIND_SONG_INTENT) && (resultCode == RESULT_OK)) {
   5:         Uri musicURI = data.getData();
   6:         getSongFromMusicCollection(musicURI);
   7:     } else {
   8:         Toast toast = Toast.makeText(this, R.string.selection_cancel,
   9:                 Toast.LENGTH_SHORT);
  10:         toast.show();
  11:     }
  12: }
Open a Text Editor

There may be cases where you application needs to use or write text to files stored on the device.  If the user may need to edit that file and you don’t want to write a text editor, here again you can try to take advantage of the Android ecosystem to launch an existing editor app on the device.  The code below shows you how to use intents to launch a text editing app.

   1: public void launchTextEditor() {
   2:     try {
   3:         Intent intent = new Intent(Intent.ACTION_EDIT);
   4:         Uri uri = Uri.parse("file:///sdcard/somefile.txt");
   5:         intent.setDataAndType(uri, "text/plain");
   6:         start Activity(intent);
   7:     } catch (ActivityNotFoundException e) {
   8:         Toast toast = Toast.makeText(this, "No editor on this device",
   9:                 Toast.LENGTH_SHORT);
  10:         toast.show();
  11:     }
  12: }

Note, in this case there is more likelihood that the Android device does not come with a text editor nor that the user has installed an independent text editor.  So again, make sure you provide a try/catch block for no such activity.  In these cases, you may find it convenient to direct users to an app store and a recommended text editor that can be downloaded and used by your app.

View a PDF

As a last example, perhaps your app creates, receives, or otherwise works with PDF files.  Below is code to launch a PDF viewer on your device and view a PDF file.

   1: public void launchPDFViewer() {
   2:     try {
   3:         Intent intent = new Intent(Intent.ACTION_VIEW);
   4:         Uri uri = Uri.parse("file:///sdcard/Download/somefile.pdf");
   5:         intent.setDataAndType(uri, "application/pdf");
   6:         start Activity(intent);
   7:     } catch (ActivityNotFoundException e) {
   8:         Toast toast = Toast.makeText(this, "No viewer on this device",
   9:                 Toast.LENGTH_SHORT);
  10:         toast.show();
  11:     }
  12: }

As you can see, the common theme with regard to all these examples is to create an Intent object containing the correct intent action and often adding the right data/type, category, or extra data to the intent.  Then launch the other party app with a call to startActivity( ) or startActivityForResult( ) with an Intent object.  Information on standard actions, categories, etc. to include in the Intent object are provide in the Intent documentation here.

Wrap Up

To be sure, there are times when you may still want to build custom functionality into your own application and not use the functionality provided by other applications.  You may need to make sure the functionality is there and cannot or do not want to rely/trust on the device to provide it or the user to install it from a 3rd party.  You may need to alter or add to the functionality provided by other applications.  You may need information or results to be returned from the functionality in a way the other app does not provide.  All good reasons to create you own capability.  When you have to build your own, or when building an app that other apps could take advantage of, consider designing and building your functionality to be launched based on intent filters.  That way, your own apps can participate in the wider Android ecosystem and offer new or improved services to the rest of the world. 

To learn more about intents and Android development in general, please join me in Intertech’s Complete Android training.

  • Asnoune Mohamed El Amine

    i need a help for my project

    i have a smart phone with Plateforme android and i went to calculing the 5 apple who call me Much

    and i’m so sorry for my bad english

{Offer-Title}

{Offer-PageContent}
Click Here