在Android SDK版本18及以下,java.nio.charset.StandardCharsets类是不可用的。在这种情况下,您可以使用Charset.forName("UTF-8")来代替 StandardCharsets.UTF_8。
下面是一个示例代码,展示了如何在Android SDK版本18上发送邮件:
import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
public class MainActivity extends AppCompatActivity {
@SuppressLint("IntentReset")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendEmail();
}
private void sendEmail() {
Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(
"mailto", "recipient@example.com", null));
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
emailIntent.putExtra(Intent.EXTRA_TEXT, "Email Body");
try {
String encodedSubject = URLEncoder.encode("Subject", Charset.forName("UTF-8").name());
String encodedBody = URLEncoder.encode("Email Body", Charset.forName("UTF-8").name());
emailIntent.setData(Uri.parse("mailto:recipient@example.com?subject=" + encodedSubject + "&body=" + encodedBody));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
startActivity(Intent.createChooser(emailIntent, "Send email..."));
}
}
在上述代码中,我们使用Charset.forName("UTF-8")来编码主题和正文,以替代StandardCharsets.UTF_8。这样可以确保在Android SDK版本18上正常发送邮件。
请确保将recipient@example.com替换为实际的收件人电子邮件地址。