I’ve got a TabHost application where the user can send an email from any of the tab activities. I want to write one class which can be instantiated from any of the activities which will handle launching the Email intent but not sure this is the ideal way to do it.
Although It saves some code duplication, it seems like a lot of overhead having to create an intent which creates another intent to launch createChooser(). Is there a better way?
Application code
Intent send = new Intent (this, Email.class);
send.putExtra ("mailto", EMAIL_ADDRESS);
send.putExtra ("subject", SUBJECT);
send.putExtra ("body", MSG_BODY);
this.startActivity (send);
Email class
public class Email extends Activity
{
@Override
protected void onCreate (Bundle savedInstanceState)
{
super.onCreate (savedInstanceState);
Log.d ("email" , " oncreate");
Bundle ex = getIntent ().getExtras ();
String mailto = ex.getString ("mailto");
String subject = ex.getString ("subject");
String body = ex.getString ("body");
if (body == null)
body = "";
if (subject == null)
subject = "";
try
{
// use the builtin chooser for users mail app or SMS
/* NOTE: AndroidManifest has android:noHistory="true" for this */
Intent sendIntent = new Intent(android.content.Intent.ACTION_SEND);
sendIntent.setType("text/plain");
sendIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String [] {mailto});
sendIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);
sendIntent.putExtra(android.content.Intent.EXTRA_TEXT, body);
startActivityForResult (Intent.createChooser(sendIntent, "Send via which Application?"), 0);
}
catch (Exception e)
{
Toast.makeText (this, "No activity was found to handle this action",Toast.LENGTH_SHORT).show();
}
}
}
Ok, so as it turns out, this was rather trivial. The sticky part was passing the Context and launching the intent from it. Hope it helps someone else.
and to call the static send method from another class: