首先如果在我们程序中要发送短信必须先声明android.permission.SEND_SMS的权限
第二发送短信,我们需要一个SmsManager的类帮助我们发送短信,注意:这个类是在android.telephony.SmsManager包下的
SmsManager smsManager=SmsManager.getDefault();
创建实例,调用
smsManager.sendTextMessage(String destinationAddress, String scAddress, String text, PendingIntent sentIntent, PendingIntent deliveryIntent);
来发送短信,值得注意的是第一个参数是短信接收者的手机号码,第二个参数是不常用不用管,第三个参数是短信的内容,
第四个参数是一个PendingIntent,短信发送成功,SmsManager会利用这个PendingIntent来发送一个广播(此广播中的
ResultCode会告诉广播接受者,此条短信是否发送成功),官方的解释如下: if not NULL this PendingIntent
is broadcast when the
message is successfully sent, or failed. The result code will be Activity.RESULT_OK
for success, or one of these errors:RESULT_ERROR_GENERIC_FAILURE、
RESULT_ERROR_RADIO_OFF、
RESULT_ERROR_NULL_PDU。
代码如下:
package com.jsako.sendsms; 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.text.TextUtils; import android.view.View; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends Activity { private EditText et_phone; private EditText et_msg; private IntentFilter sendFilter; private SendStatusReceiver sendStatusReceiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); et_phone = (EditText) findViewById(R.id.et_phone); et_msg = (EditText) findViewById(R.id.et_msg); sendFilter =new IntentFilter("SEND_SMS"); sendStatusReceiver=new SendStatusReceiver(); //动态注册广播接收者 registerReceiver(sendStatusReceiver, sendFilter); } @Override protected void onDestroy() { super.onDestroy(); //取消注册广播接收者 unregisterReceiver(sendStatusReceiver); sendStatusReceiver=null; } public void send(View view){ String phone=et_phone.getText().toString().trim(); String msg=et_msg.getText().toString().trim(); if(TextUtils.isEmpty(phone)||TextUtils.isEmpty(msg)){ Toast.makeText(this,"手机号码或短信内容不能为空", 0).show(); } SmsManager smsManager=SmsManager.getDefault(); Intent intent=new Intent("SEND_SMS"); //获得一个能发出广播的意图 PendingIntent pi=PendingIntent.getBroadcast(this, 0, intent, 0); smsManager.sendTextMessage(phone, null, msg, pi,null ); } private class SendStatusReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if(this.getResultCode()==RESULT_OK){ //如果结果集为RESULT_OK说明消息发送成功 Toast.makeText(getApplicationContext(), "发送成功", 0).show(); }else{ Toast.makeText(getApplicationContext(), "发送失败", 0).show(); } } } }
时间: 2024-10-29 00:16:52