Android短信的发送和接收监听

时间:2021-11-25 12:36:22
 1 /**发送与接收的广播**/
 2     String SENT_SMS_ACTION = "SENT_SMS_ACTION";
 3     String DELIVERED_SMS_ACTION = "DELIVERED_SMS_ACTION";
 4  
 5     private BroadcastReceiver sendMessage = new BroadcastReceiver() {
 6  
 7         @Override
 8         public void onReceive(Context context, Intent intent) {
 9             Log.i("TAG", "send。。" + intent.getAction() + "---" + getResultCode() + "---" + getResultData());
10             //判断短信是否发送成功  
11             switch (getResultCode()) {
12             case Activity.RESULT_OK:
13                 Toast.makeText(context, "短信发送成功", Toast.LENGTH_SHORT).show();
14                 break;
15             default:
16                 Toast.makeText(mContext, "发送失败", Toast.LENGTH_LONG).show();
17                 break;
18             }
19         }
20     };
21  
22     private BroadcastReceiver receiver = new BroadcastReceiver() {
23         @Override
24         public void onReceive(Context context, Intent intent) {
25             Log.i("TAG", "receiver。。" + intent.getAction() + "---" + getResultCode() + "---" + getResultData());
26             //表示对方成功收到短信  
27             Toast.makeText(mContext, "对方接收成功", Toast.LENGTH_LONG).show();
28         }
29     };
30  
31     /**  
32      * 参数说明  
33      * destinationAddress:收信人的手机号码  
34      * scAddress:发信人的手机号码   
35      * text:发送信息的内容   
36      * sentIntent:发送是否成功的回执,用于监听短信是否发送成功。  
37      * DeliveryIntent:接收是否成功的回执,用于监听短信对方是否接收成功。  
38      */
39     private void sendSMS(String phoneNumber, String message) {
40         // ---sends an SMS message to another device---  
41         SmsManager sms = SmsManager.getDefault();
42  
43         // create the sentIntent parameter  
44         Intent sentIntent = new Intent(SENT_SMS_ACTION);
45         PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, sentIntent, 0);
46  
47         // create the deilverIntent parameter  
48         Intent deliverIntent = new Intent(DELIVERED_SMS_ACTION);
49         PendingIntent deliverPI = PendingIntent.getBroadcast(this, 0, deliverIntent, 0);
50  
51         //如果短信内容超过70个字符 将这条短信拆成多条短信发送出去  
52         if (message.length() > 70) {
53             ArrayList<String> msgs = sms.divideMessage(message);
54             for (String msg : msgs) {
55                 sms.sendTextMessage(phoneNumber, null, msg, sentPI, deliverPI);
56             }
57         } else {
58             sms.sendTextMessage(phoneNumber, null, message, sentPI, deliverPI);
59         }
60     }