我正在尝试创建一个小型应用程序,用户可以在其中键入收件人,主题,消息,如果愿意,还可以附加文件。我遇到了一个小问题,我无法自由选择任何文件。我浏览了我的文件夹并找到图像和PDF文件,但它们均不可单击,我无法选择(由于某些原因它们已变灰)。
我曾经可以选择一个文件(不记得它是什么类型),但是我从Outlook应用程序中收到了IO错误,由于某种原因它无法处理该文件。
public class MainActivity extends AppCompatActivity {
private static final int PICKFILE_REQUEST_CODE = 8778;
private EditText mEditTextTo;
private EditText mEditTextSubject;
private EditText mEditTextMessage;
private Button sendBtn;
private Button fileBtn;
private String filePath = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mEditTextTo = (EditText)findViewById(R.id.edit_text_to);
mEditTextSubject = (EditText)findViewById(R.id.edit_text_subject);
mEditTextMessage = (EditText)findViewById(R.id.edit_text_message);
sendBtn = (Button)findViewById(R.id.sendBtn);
fileBtn = (Button)findViewById(R.id.fileBtn);
sendBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendMail();
}
});
fileBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("file/*");
startActivityForResult(intent, PICKFILE_REQUEST_CODE);
}
});
}
private void sendMail() {
String recepientList = mEditTextTo.getText().toString();
String[] recepient = recepientList.split(",");
String subject = mEditTextSubject.getText().toString();
String message = mEditTextMessage.getText().toString();
Intent sendEmailIntent = new Intent(Intent.ACTION_SEND);
sendEmailIntent.putExtra(Intent.EXTRA_EMAIL, recepient);
sendEmailIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
sendEmailIntent.putExtra(Intent.EXTRA_TEXT, message);
sendEmailIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new
File(filePath)));
sendEmailIntent.setType("text/plain");
startActivity(Intent.createChooser(sendEmailIntent, "Choose email
client"));
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
filePath = data.getDataString();
super.onActivityResult(requestCode, resultCode, data);
}
}
答案 0 :(得分:0)
您可以使用以下代码:
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_EMAIL, new String[] {"email@example.com"});
intent.putExtra(Intent.EXTRA_SUBJECT, "subject here");
intent.putExtra(Intent.EXTRA_TEXT, "body text");
File root = Environment.getExternalStorageDirectory();
File file = new File(root, xmlFilename);
if (!file.exists() || !file.canRead()) {
Toast.makeText(this, "Attachment Error", Toast.LENGTH_SHORT).show();
finish();
return;
}
Uri.fromFile(file);
intent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(intent, "Send email..."));