android - 为什么电子邮件 Intent 在公共(public)(非 Activity )类中不起作用

标签 android android-intent

此代码在 Activity 类中完美运行,但如果我将此代码移至 Common(非 Activity)类,则会收到此错误:

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

这是代码:

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

    }

这就是我从 Activity 中调用的方式:

 Common.emailIntend( getApplicationContext() );

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

请告诉我我是否做错了什么。

最佳答案

问题是您在错误的 Intent 上调用了 addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
这与使用 getApplicationContext() 相结合,导致了错误。

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

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

另请注意,我还必须稍微修改您的代码才能使选择器正常工作,您的原始代码对我不起作用,即使在 Activity 中也是如此。

以下代码适用于我,甚至使用 getApplicationContext() 作为传入的上下文:

public static void sendEmail(Context context){
    String uriText =
            "mailto:<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3e4a5b4d4a7e59535f5752105d5153" rel="noreferrer noopener nofollow">[email protected]</a>" +
                    "?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 for sending an email

startActivity within a subclass of Application

关于android - 为什么电子邮件 Intent 在公共(public)(非 Activity )类中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31172447/

相关文章:

android - 为什么在匿名子类上使用 Kotlin "by"?

android - 重启后防止 USB_DEVICE_ATTACHED 启动应用程序

android - 如何从启动另一个应用程序的应用程序中获取额外的 Intent ?

android 向特定联系人发送 Intent (whatsapp、短信、远足等)

java - ArrayList<custom-object> 的 Parcelable 实现

android - 如何在 android 中启动默认音乐应用程序以播放特定歌曲?

java - 不显示按钮的背景

android - 与在Android中扩大 Activity 和扩大 View 有什么区别?

android - 后退按钮后隐藏 fragment

java - Android 抽屉导航上的自定义工具栏