第三章:交互式通信服务与手机控制(发送Email)
效果:
发送成功
(注:发送前将自己手机或手机模拟器设置好信箱)
设置流程我用的是163的信箱。
图:
main.xml
package send.email.test;import java.util.regex.Matcher;import java.util.regex.Pattern;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.view.KeyEvent;import android.view.View;import android.widget.Button;import android.widget.EditText;public class SendEmailTest extends Activity {private EditText receiving;private EditText accessories;private EditText title;private EditText text;private Button button;private String[] reciver;private String[] subject;private String emailCc;private String emailBody; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); /** 载入main.xml*/ setContentView(R.layout.main); /**通过id找到EditText组件*/ receiving =(EditText)findViewById(R.id.receiving); accessories=(EditText)findViewById(R.id.accessories); title=(EditText)findViewById(R.id.title); text=(EditText)findViewById(R.id.text); button=(Button)findViewById(R.id.send); /**设置Button按钮点击事件*/ receiving.setOnKeyListener(new EditText.OnKeyListener() { public boolean onKey(View v,int keyCode,KeyEvent event){ /**Email格式是否正确*/ if(isEmail(receiving.getText().toString())){ /**设置Button按钮为可点击*/ button.setEnabled(true); }else{ /**设置Button按钮不可点击*/ button.setEnabled(false); }return false; }}); button.setOnClickListener(new Button.OnClickListener(){ public void onClick(View v){ /**通过Intent发送Email*/ Intent intent=new Intent(android.content.Intent.ACTION_SEND); /** * intent.setType("text/plain"); 模拟器请使用这行 * intent.setType("message/rfc822") ; 真机上使用这行 */ intent.setType("plain/text"); /**取得收件人地址 主旨正文*/ reciver=new String[]{ receiving.getText().toString() }; subject=new String[]{accessories.getText().toString()}; emailCc=title.getText().toString(); emailBody=text.getText().toString(); /**将字符串放进intent*/ intent.putExtra(android.content.Intent.EXTRA_EMAIL, reciver); intent.putExtra(android.content.Intent.EXTRA_CC, subject); intent.putExtra(android.content.Intent.EXTRA_SUBJECT, emailCc); intent.putExtra(android.content.Intent.EXTRA_TEXT, emailBody); /**打开Email将参数传入*/ startActivity(Intent.createChooser(intent, getResources().getString(R.string.send))); } }); } /**匹配Email格式是否正确*/ public static boolean isEmail(String email){ String strPattern="\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*"; Pattern pattern=Pattern.compile(strPattern); Matcher matcher=pattern.matcher(email); return matcher.find(); }}