Thursday, April 17, 2014

How to start an Activity from within a Service

First, if you plan on doing this, please read this bit about interrupting the user: http://developer.android.com/guide/practices/seamlessness.html#interrupt

The trick is to set the intent's flag for FLAG_ACTIVITY_NEW_TASK. Also, as you probably already know, all life cycle methods like onCreate are executed on the UI thread which is required to start an Activity.

Here's an example:
  public void onCreate(){
    super.onCreate();
    Intent intent = new Intent("com.example.email.compose");
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //This is necessary!
    intent.putExtra("Contacts_ID", 0);
    startActivity(intent);
  }