SmsManager smsMagager = SmsManager.getDefault(); // 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); String tel = editTel.getText().toString(); String msg = editMsg.getText().toString(); smsMagager.sendTextMessage( tel , null , msg , sentPI , deliverPI );
先上代码,上述功能实现了Android发送短信到指定号码的功能(sentPI为了获得发送报告的,DeliverPI为了获得对方接受到之后返回的报告的),区别就是:发送报告,只是短信发送出去,对面是否接受不关心;接收报告:就是发送方的短信发送到对方手机上之后,对方手机会返回给运营商一个信号,告知运营商收到短信,运营商再把这个信号发给发送方,发送方得到这个信号之后,
同时需要给这个应用权限
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.SEND_SMS" />
若想把刚刚发送的短信插入到数据库中,需要增加以下内容
ContentValues values = new ContentValues();
//发送时间
values.put("date", System.currentTimeMillis());
//阅读状态
values.put("read", 0);
//1为收 2为发
values.put("type", 2);
//送达号码
values.put("address",tel);
//送达内容
values.put("body", msg);
//插入短信库
getContentResolver().insert(Uri.parse("content://sms/sent"), values);
<uses-permission android:name="android.permission.WRITE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
开始我担心,只插入到一个表里会不会有问题,后来参看了TelephonyProvider发现我的想法是多余的,因为TelephonyProvider会把数据插入到每个表中。
注册两个广播~得到发送报告和接收报告~
@Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); registerReceiver(sendMessage, new IntentFilter(SENT_SMS_ACTION)); registerReceiver(receiver, new IntentFilter(DELIVERED_SMS_ACTION)); }
BroadcastReceiver sendMessage = new BroadcastReceiver() { @Override public void onReceive(Context c, Intent intent) { // TODO Auto-generated method stub //判断短信是否发送成功 switch (getResultCode()) { case Activity.RESULT_OK: Toast.makeText(c, "短信发送成功", Toast.LENGTH_SHORT).show(); break; default: Toast.makeText(c, "发送失败", Toast.LENGTH_LONG).show(); break; } } }; BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { //表示对方成功收到短信 Toast.makeText(context, "对方接收成功",Toast.LENGTH_LONG).show(); } };