Green Apple
Green Apple

Reputation: 101

Why is the email Intent not working from Common (non Activity) class

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.

Upvotes: 2

Views: 754

Answers (1)

Daniel Nugent
Daniel Nugent

Reputation: 43322

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:[email protected]" +
                    "?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

Upvotes: 2

Related Questions