发送短信:
package com.henii.SMS; import java.util.ArrayList; import android.app.Activity; import android.os.Bundle; import android.telephony.SmsManager; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; //!!!可以通过启动两个模拟器进行测试,发送短信时就拨另一个的端口号(如5554等)就行了!!! //在AndroidManifest.xml中要添加权限: public class SMSActivity extends Activity { private EditText mobileText; private EditText contText; private Button sendBtn; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //根据id找到控件并实例化它 mobileText = (EditText)findViewById(R.id.MobileEditText); contText = (EditText)findViewById(R.id.ContEditText); sendBtn = (Button)findViewById(R.id.SendButton); //发送按钮的处理事件 sendBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String content = contText.getText().toString(); String mobile = mobileText.getText().toString(); //获得发送短信的管理器,使用的是android.telephony.SmsManager SmsManager smsManager = SmsManager.getDefault(); //如果短信内容过长则分段发送 if(content.length() > 70){ //使用短信管理器进行短信内容的分段,返回分成的段 ArrayList contents = smsManager.divideMessage(content); for(String msg : contents){ //使用短信管理器发送短信内容 //参数一为短信接收者 //参数三为短信内容 //其他可以设为null smsManager.sendTextMessage(mobile, null, msg, null, null); } //否则一次过发送 } else{ smsManager.sendTextMessage(mobile, null, content, null, null); } //吐司,用来显示发送成功的提示 Toast.makeText(SMSActivity.this, R.string.sucTxt, Toast.LENGTH_SHORT).show(); } }); //!!!可以通过启动两个模拟器进行测试,发送短信时就拨另一个的端口号(如5554等)就行了!!! } }
注册权限permission:
< uses-permission android:name="android.permission.SEND_SMS"/ > < uses-permission android:name="android.permission.RECEIVE_SMS"/ >
接收短信:首先创建一个接收短信的Java类文件“ReceiverDemo.java”并继承”BroadcastReceiver”
public void onReceive(Context context, Intent intent) //重写内容如下: private static final String strRes = "android.provider.Telephony.SMS_RECEIVED"; @Override public void onReceive(Context context, Intent intent) { /* * 判断是否是SMS_RECEIVED事件被触发 */ if (intent.getAction().equals(strRes)) { StringBuilder sb = new StringBuilder(); Bundle bundle = intent.getExtras(); if (bundle != null) { Object[] pdus = (Object[]) bundle.get("pdus"); SmsMessage[] msg = new SmsMessage[pdus.length]; for (int i = 0; i < pdus.length; i++) { msg[i] = SmsMessage.createFromPdu((byte[]) pdus[i]); } for (SmsMessage currMsg : msg) { sb.append("您收到了来自:【"); sb.append(currMsg.getDisplayOriginatingAddress()); sb.append("】的信息,内容:"); sb.append(currMsg.getDisplayMessageBody()); } Toast toast = Toast.makeText(context, "收到了短消息: " + sb.toString(),Toast.LENGTH_LONG); toast.show(); } } }