发送短信的方法
public class MessageActivity extends Activity
{
//发送短信
private EditText to;
private EditText msgInput;
private Button send;
//对短信的发送状态进行监控
private IntentFilter sendFilter;
private SendStatusReceiver sendStatusReceiver;
@Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.m_message);
//发送短信的处理逻辑
to = (EditText) findViewById(R.id.to);
msgInput = (EditText) findViewById(R.id.msg_input);
send = (Button) findViewById(R.id.send);
//监测短信发送状态的广播
sendFilter = new IntentFilter();
sendFilter.addAction("SENT_SMS_ACTION");
sendStatusReceiver = new SendStatusReceiver();
registerReceiver(sendStatusReceiver,sendFilter);
send.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
//发送短信
//当按钮被点击时,首先调用SmsManager的getDefault()方法获取到SmsManager的实例,
//然后再调用它的sendTextMessage()方法就可以发送短信了。这个方法接收五个参数:第一个用于指定接收人的手机号码,
//第三个用于指定信息的内容,第四个参数用来对短信的发送状态进行监控。
SmsManager smsManager = SmsManager.getDefault();
//监测发送状态
//调用PendingIntent的getBroadcast()方法获取到一个PendingIntent对象,将它作为第四个参数传递到
//sendTextMessage()方法中
Intent sentIntent = new Intent("SENT_SMS_ACTION");
PendingIntent pendingIntent = PendingIntent.getBroadcast(MessageActivity.this,
0, sentIntent, 0);
smsManager.sendTextMessage(to.getText().toString(), null,
msgInput.getText().toString(),pendingIntent, null);
//如果想要发送长度超过160个字符的短信需要将短信分割成多条短信来发送,使用SmsManager的
//sendMultipartTextMessage()方法可以实现。
}
});
}
@Override
protected void onDestroy()
{
// TODO Auto-generated method stub
super.onDestroy();
//取消注册(发送短信)
unregisterReceiver(sendStatusReceiver);
}
//监测短信发送状态的广播接收器
class SendStatusReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
// TODO Auto-generated method stub
if(getResultCode() == RESULT_OK)
{
//短信发送成功
Toast.makeText(context, "发送成功!", Toast.LENGTH_SHORT).show();
}
else
{
//短信发送失败
Toast.makeText(context, "发送失败!", Toast.LENGTH_SHORT).show();
}
}
}
}
xml布局
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:padding="10dp"
android:text="收件人:" />
<EditText
android:id="@+id/to"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="1" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp" >
<EditText
android:id="@+id/msg_input"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="1" />
<Button
android:id="@+id/send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:text="发送" />
</LinearLayout>