您的位置:首页 > 移动开发 > Android开发

Android发送接收短信的代码示例

2010-12-23 12:04 543 查看
1、SMS Activity 短信发送Class

package cn.dccssq;

import java.util.List;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class SMS extends Activity {

String SENT_SMS_ACTION="SENT_SMS_ACTION";
String DELIVERED_SMS_ACTION="DELIVERED_SMS_ACTION";

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

Button btn = (Button)findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {

public void onClick(View arg0) {
// TODO Auto-generated method stub
EditText telNoText =(EditText)findViewById(R.id.telNo);
EditText contentText = (EditText)findViewById(R.id.content);

String telNo = telNoText.getText().toString();
String content = contentText.getText().toString();
if (validate(telNo, content))
{
sendSMS(telNo, content);
}else{
//					AlertDialog.Builder builder =  new AlertDialog.Builder(SMS.this);
//					builder.setMessage("Please enter both phone number and message.")
//					.setTitle("Error")
//							.setCancelable(false)
//							.setNegativeButton("OK",
//									new DialogInterface.OnClickListener() {
//										public void onClick(
//												DialogInterface dialog,
//												int id) {
//											dialog.cancel();
//										}
//									});
//					AlertDialog alert = builder.create();
//					alert.show();
}
}
});
}

/**
* Send SMS
* @param phoneNumber
* @param message
*/
private void sendSMS(String phoneNumber, String message) {

//create the sentIntent parameter
Intent sentIntent = new Intent(SENT_SMS_ACTION);
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, sentIntent,
0);
// create the deilverIntent parameter
Intent deliverIntent = new Intent(DELIVERED_SMS_ACTION);
PendingIntent deliverPI = PendingIntent.getBroadcast(this, 0,
deliverIntent, 0);

SmsManager sms = SmsManager.getDefault();
if (message.length() > 70) {
List<String> msgs = sms.divideMessage(message);
for (String msg : msgs) {
sms.sendTextMessage(phoneNumber, null, msg, sentPI, deliverPI);
}
} else {
sms.sendTextMessage(phoneNumber, null, message, sentPI, deliverPI);
}
Toast.makeText(SMS.this, R.string.message, Toast.LENGTH_LONG).show();

//register the Broadcast Receivers
registerReceiver(new BroadcastReceiver(){
@Override
public void onReceive(Context _context,Intent _intent)
{
switch(getResultCode()){
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(),
"SMS sent success actions",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getBaseContext(),
"SMS generic failure actions",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getBaseContext(),
"SMS radio off failure actions",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getBaseContext(),
"SMS null PDU failure actions",
Toast.LENGTH_SHORT).show();
break;
}
}
},
new IntentFilter(SENT_SMS_ACTION));
registerReceiver(new BroadcastReceiver(){
@Override
public void onReceive(Context _context,Intent _intent)
{
Toast.makeText(getBaseContext(),
"SMS delivered actions",
Toast.LENGTH_SHORT).show();
}
},
new IntentFilter(DELIVERED_SMS_ACTION));

}

public boolean validate(String telNo, String content){

if((null==telNo)||("".equals(telNo.trim()))){
Toast.makeText(this, "please input the telephone No.!",Toast.LENGTH_LONG).show();
return false;
}
if(!checkTelNo(telNo)){
Toast.makeText(this, "please input the right telephone No.!",Toast.LENGTH_LONG).show();
return false;
}
if((null==content)||("".equals(content.trim()))){
Toast.makeText(this, "please input the message content!",Toast.LENGTH_LONG).show();
return false;
}
return true;
}

public boolean checkTelNo(String telNo){
if("5556".equals(telNo)){
return true;
}else{
String reg ="^0{0,1}(13[0-9]|15[0-9])[0-9]{8}$";
return telNo.matches(reg);
}
}
}


※1、为了测试模拟器间的通信,在checkTelNo方法中加入了以下代码的判断,实际开发中不需要

if("5556".equals(telNo)){
return true;
}

※2、Message信息均为Hard coding,为了便于多语言化和避免message的重复定义,在实际开发中应将message定义在strin.xml中。

2、ReceiverDemo 短信接收Class

package cn.dccssq;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;

public class ReceiverDemo extends BroadcastReceiver {

private static final String strRes = "android.provider.Telephony.SMS_RECEIVED";

@Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
if(strRes.equals(arg1.getAction())){
StringBuilder sb = new StringBuilder();
Bundle bundle = arg1.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 curMsg:msg){
sb.append("You got the message From:【");
sb.append(curMsg.getDisplayOriginatingAddress());
sb.append("】Content:");
sb.append(curMsg.getDisplayMessageBody());
}
Toast.makeText(arg0,
"Got The Message:" + sb.toString(),
Toast.LENGTH_SHORT).show();
}
}
}

}


3、main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/mobile"
/>
<EditText
android:id="@+id/telNo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:numeric="integer"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/content"
/>
<EditText
android:id="@+id/content"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:minLines="3"
/>
<Button
android:id="@+id/btn"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/button"
/>
</LinearLayout>


4、strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World, SMS!</string>
<string name="app_name">SMS</string>
<string name="mobile">Please input the TEL No.</string>
<string name="content">Please input the SMS content.</string>
<string name="button">SEND</string>
<string name="message">send successfully!</string>
</resources>


5、AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="cn.dccssq"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".SMS"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".ReceiverDemo" android:enabled="true" >
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
</application>
<uses-sdk android:minSdkVersion="7" />
<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
</manifest>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: