转自:http://www.reasono.com/?p=318
实验环境:
windows 7
Android Developer Tools
Build: v21.1.0-569685
今日在开发一个小app的时候遇到一个问题:
该app需要实现本机发送短信,遂,通过
SmsManager + PendingIntent.getBroadcast 的方式实现,因为短信队列里包含多个号码,且发送完毕后需要更新发送状态,所以需要在BroadcastReceiver回调中得到发送短信的ID,大体实现如下(大家也可以参考下具体发送短信的机制):
1、接收短信发送后的回调函数:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
|
private
private
private
public
sms sendBroadcastReceiver new
@Override public
Bundle Object[] String "" ; String "" ; for ( int
0 ; { String if
"phone" )) phone_number } if
"sms_id" )) sms_id } } switch
case
receiveSmsLog( "SEND" , "to:"
"- ); break ; case
receiveSmsLog( "SEND" , "to:"
"- ); break ; case
receiveSmsLog( "SEND" , "to:"
"- ); break ; case
receiveSmsLog( "SEND" , "to:"
"- ); break ; } } }; registerReceiver(sendBroadcastReceiver new
deliveryBroadcastReceiver new
@Override public
Bundle Object[] String "" ; String "" ; for ( int
0 ; { String if
"phone" )) phone_number } if
"sms_id" )) sms_id } } Log.d( "sms_id" , "" ); receiveSmsLog( "DELIVER" , "to:"
"- ); } }; registerReceiver(deliveryBroadcastReceiver, new
} |
2、开始发送短信:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
private
0 ; public
final
final
Intent new
sentIntent.putExtra( "sms_id" , sentIntent.putExtra( "phone" , Intent new
deliverIntent.putExtra( "sms_id" , deliverIntent.putExtra( "phone" , pend_times++; PendingIntent this , PendingIntent this , if
70 ) ArrayList<String> for
sms.sendTextMessage(phone_number, null , } } else
sms.sendTextMessage(phone_number, null , } } |
开始的时候多次发送短信成功,但是intent中的数据总是第一次传入的数据,其后就不能更新,通过google多次,尽一天的时间得到的结论是:
需要在PendingIntent.getBroadcast函数中设置第4个参数为 PendingIntent.FLAG_UPDATE_CURRENT
即:PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, sentIntent, PendingIntent.FLAG_UPDATE_CURRENT);
但是我这里还是不能成功,百思不得其解啊。
于是就修改了第二个参数requestCode,即
1
2
3
4
|
private
0 ; pend_times++; PendingIntent this , |
测试通过,哈哈~~。
有的同学还提出修改了requestCode也没起作用,我建议同时修改
PendingIntent intent= PendingIntent.getBroadcast(Context context, int requestCode, Intent intent, int flags)的requestCode 和flags试试,好运~~