Showing posts with label intent. Show all posts
Showing posts with label intent. Show all posts

Sunday, December 7, 2008

Sending SMS using Android Intents

You've got an Android application and you want to send an email, sms and mms via your application. But you don't want to have to write a whole mail/mms/sms client. Thankfully Android provides a flexible way to forward responsibilities onto other applications installed on the device.

Android uses the concept of intents to enable applications to make requests for other applications to handle their tasks. For example, an application finds your location and wants to send it as a map via MMS. 

This can done by by constructing an Intent object, loading it up with the appropriate action, data and sending off to the operating system. 

Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.setData(Uri.parse("scheme://data"));
sendIntent.setType("mime/type");
sendIntent.putExtra("key", "value");
startActivity(sendIntent); 

Android then decides which activity can best handle this intent based on various attributes such as scheme (mailto, http) and mime type (image/png). 

If multiple applications could handle the intent (if you're sending an image), then you can even prompt the user to choose which application they want to use (email,MMS, IM)

startActivity(Intent.createChooser(sendIntent, "Title: ");

This all sounds too easy to be true. And it is. The reality is that in order to invoke mail,sms and mms I have needed to dive into the Android source code (thank goodness for Open Source!). I wanted to invoke each of these applications, filling in as much of the content as possible. The documentation for Intents even suggests this is possible to attach images, set subjects and body text. 

To invoke the SMS application via intents you have to do the following:
  • Set the action to ACTION_VIEW
  • Set the mime type to vnd.android-dir/mms-sms
  • Optionally add any text by adding an extra String with the key sms_body 
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.putExtra("sms_body", "The SMS text"); 
sendIntent.setType("vnd.android-dir/mms-sms");
startActivity(sendIntent);   

Android also enables you to send SMS directly using an API without bringing up the SMS application. However it is much more transparent to the user to allow them to see what they are sending and maybe add or edit before it goes out. Using Intents also means you can minimise the permissions your application requires.

Sending MMS and email is a much longer story which I'll get into in some later posts.  Stay tuned!