2

This code works perfectly in the Activity Class, but if I move this code to Common (non Activity) class I'm getting this error:

Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?

Here is the code:

public static void emailIntend(Context context) {

        Intent emailIntent = new Intent(Intent.ACTION_SENDTO, null);

        emailIntent.putExtra(Intent.EXTRA_SUBJECT, context.getString(R.string.string_email_send_feedback_subject));
        String[] receipients = new String[1];
        receipients[0] = context.getString(R.string.string_email);
        emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, receipients);

        emailIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        context.startActivity(Intent.createChooser(emailIntent, "Send email to the developer..."));

    }

And this is how I am calling from the Activity:

 Common.emailIntend( getApplicationContext() );

I tried replacing getApplicationContext() with this, but no help.

Kindly, tell me if I am doing something not correct.

Green Apple
  • 101
  • 10
  • Please explain what "this does not works" means. Also, AFAIK, you need a `mailto:` `Uri` instead of `EXTRA_EMAIL` on `ACTION_SENDTO`. – CommonsWare Jul 01 '15 at 22:03
  • @CommonsWare This is error I am getting `Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?` Otherwise the codes fine in Activity class. – Green Apple Jul 01 '15 at 22:23
  • @DanielNugent Yes, updated. Thanks. – Green Apple Jul 01 '15 at 22:24

1 Answers1

2

The problem is that you're calling addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) on the wrong Intent.
That, combined with using getApplicationContext(), is causing the error.

The call to Intent.createChooser() returns a new Intent, and that's the one that needs the FLAG_ACTIVITY_NEW_TASK flag, since it's the one that you're passing to startActivity().

Note that FLAG_ACTIVITY_NEW_TASK wasn't needed if I passed in an Activity context to the method (this in the Activity);

Also note that I also had to modify your code a bit to get the chooser to work correctly, your original code didn't work for me, even in an Activity.

The following code works for me, even using getApplicationContext() as the context passed in:

public static void sendEmail(Context context){
    String uriText =
            "mailto:test@gmail.com" +
                    "?subject=" + Uri.encode("test subject");
    Uri uri = Uri.parse(uriText);

    Intent emailIntent = new Intent(Intent.ACTION_SENDTO, uri);

    Intent i = Intent.createChooser(emailIntent, "Send email to the developer...");
    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    context.startActivity(i);
}

References:

ACTION_SENDTO for sending an email

startActivity within a subclass of Application

Community
  • 1
  • 1
Daniel Nugent
  • 43,104
  • 15
  • 109
  • 137