如何正确实现电子邮件意图

时间:2017-07-29 14:51:17

标签: android email android-intent

我搜索了堆栈溢出和google documentation的电子邮件意图,发现代码是代码:
但是,每次我在我的活动中点击“提交”,我都会选择gmail。它在gmail中打开一封新邮件,但它只会输入收据地址。缺少主题和文本(姓名,电子邮件地址和反馈文本)。

public void composeEmail(String[] addresses, String subject) {
    Intent intent = new Intent(Intent.ACTION_SENDTO);
    intent.setData(Uri.parse("mailto:")); // only email apps should handle this
    intent.putExtra(Intent.EXTRA_EMAIL, addresses);
    intent.putExtra(Intent.EXTRA_SUBJECT, subject);
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivity(intent);
    }
}

我将其实现为以下代码。如果没有安装应用程序,则在else之后的所有内容都会弹出AlertDialog。

public class EmailActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.acitvity_email);

    final EditText nameField = (EditText) findViewById(R.id.editTextName);
    final EditText addressField = (EditText) findViewById(R.id.editTextEmail);
    final EditText subjectField = (EditText) findViewById(R.id.editTextSubject);
    final EditText feedbackField = (EditText) findViewById(R.id.editTextFeedback);
    final Button submitFeedback = (Button) findViewById(R.id.buttonSubmitFeedback);

    final String name = nameField.getText().toString();
    final String address = addressField.getText().toString();
    final String subject = subjectField.getText().toString();
    final String feedback = feedbackField.getText().toString().concat(name).concat(address);

    submitFeedback.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) {
            composeFeedback(subject, feedback);
        }
    });
}

public void composeFeedback(String subject, String feedback){
    Intent intent = new Intent(Intent.ACTION_SENDTO);
    intent.setData(Uri.parse("mailto:" + "mydeveloperemail@gmail.com"));
    intent.putExtra(Intent.EXTRA_TEXT,feedback);
    intent.putExtra(Intent.EXTRA_SUBJECT, subject);

    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivity(intent);
    } else {
        final Drawable fail = getResources().getDrawable(R.drawable.ic_fail);
        AlertDialog.Builder builder = new AlertDialog.Builder(EmailActivity.this);
        builder.setTitle("Fehler");
        builder.setIcon(fail);
        builder.setMessage("Keine Email App verfügbar!");
        builder.setCancelable(false);
        builder.setNeutralButton("Okay", new DialogInterface.OnClickListener(){
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        AlertDialog alert = builder.create();
        alert.show();
    }
}

编辑:@CommonsWare在他的回答中指出删除了意图过滤器

1 个答案:

答案 0 :(得分:0)

ACTION_SENDTOnot required to use any extras。将您的数据放入mailto: Urithe way a Web page would

  

在android清单中,我声明了对活动的意图过滤器

除非正在编写电子邮件应用,例如Gmail,否则此<intent-filter>对用户来说既不必要又有害。