为什么电子邮件Intent在Common(非活动)类中不起作用



这段代码在活动类中运行良好,但如果我将这段代码移到Common(非活动)类,我会收到以下错误:

从活动上下文外部调用startActivity()需要ACTIVITY_NEW_TASK标志。这真的是你想要的吗?

这是代码:

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..."));
    }

这就是我在活动中打电话的方式:

 Common.emailIntend( getApplicationContext() );

我尝试用this替换getApplicationContext(),但没有任何帮助。

如果我做的事情不对,请告诉我。

问题是您调用addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)的Intent错误
再加上使用getApplicationContext(),导致了这个错误。

Intent.createChooser()的调用返回一个新的Intent,这是需要FLAG_ACTIVITY_NEW_TASK标志的一个,因为它是您传递给startActivity()的标志。

请注意,如果我将Activity上下文传递给方法(Activity中的this),则不需要FLAG_ACTIVITY_NEW_TASK

还要注意的是,我还必须对您的代码进行一些修改,以使选择器正确工作,您的原始代码对我来说不起作用,即使在"活动"中也是如此。

以下代码对我有效,即使使用getApplicationContext()作为传入的上下文:

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);
}

参考文献:

发送电子邮件的ACTION_SENDTO

应用程序的子类内的startActivity

最新更新