3

I'm trying to open the email app from my application and get an error.

Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag.

The problem is, I set FLAG_ACTIVITY_NEW_TASK. I'm also tried to addFlags

This is my code:

 private void mailTo(String mail) {
    Intent i = new Intent(Intent.ACTION_SEND).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    i.setType("message/rfc822");
    i.putExtra(Intent.EXTRA_EMAIL  , new String[]{mail});
    try {
            context.startActivity(Intent.createChooser(i, ""));
} catch (ActivityNotFoundException ex) {
        Toast.makeText(context, ex.getMessage(), Toast.LENGTH_LONG).show();
    }
}

I must note that, in the same class I have more working Intent Actions.

private void callTo(String number) {
    Intent callIntent = new Intent(Intent.ACTION_CALL).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    callIntent.setData(Uri.parse("tel:" + number));
    context.startActivity(callIntent);
}

And:

private void smsTo(String phoneNumber) {
    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("sms:" + phoneNumber)).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(intent);
}
Fedaykin
  • 4,482
  • 3
  • 22
  • 32
Shachar87
  • 149
  • 1
  • 1
  • 11

2 Answers2

1

Have you try calling the startActivity() without getting it from the context() object? context() has the current state of the application, so you might not be sure from where you are starting the intent. So it would be:

startActivity(Intent.createChooser(i, ""));

And with that, remove the flag

Intent i = new Intent(Intent.ACTION_SEND);

EDIT

Since you are calling the intent() from an Activity() that is not the MainActivity(), try passing the context() parameter to the constructor of your class.

Context context;

public MyAdapaterClass(Context context) {
this.context=context;
}

And then initiate the intent() like this:

Intent i = new Intent(context, MainActivity.class);
Jose Bernhardt
  • 887
  • 1
  • 10
  • 24
  • I dont understand your answer. this class extends from BaseAdapter, so the context I get from the parent. – Shachar87 Sep 05 '16 at 21:14
  • Somehow I understood that you were calling the Intent from the MainActivity class, I'll posted my changes. – Jose Bernhardt Sep 05 '16 at 21:31
  • As I said I get the context from the perent already. about the intent exmple, Its not what I need. I need Intent for Intent.ACTION_SEND. – Shachar87 Sep 05 '16 at 21:51
0

Someone told me Intent.createChooser is not coping the flags.

So I needed to follows Intent tmp = Intent.createChooser... and re-set the flag on tmp.

I replaced :

context.startActivity(Intent.createChooser(i, ""));

To:

Intent tmp = Intent.createChooser(i, "").setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(tmp);

And removed:

i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Shachar87
  • 149
  • 1
  • 1
  • 11