如何从广播接收器发送短信并检查其状态?
所以这是我的 BroadcastReceiver
public class IncomingSMSListener extends BroadcastReceiver {
private static final String SMS_EXTRA_NAME = "pdus";
@Override
public void onReceive(Context context, Intent intent) {
SmsMessage[] messages = fetchSMSMessagesFromIntent(intent);
}
private SmsMessage[] fetchSMSMessagesFromIntent(Intent intent) {
ArrayList<SmsMessage> receivedMessages = new ArrayList<SmsMessage>();
Object[] messages = (Object[]) intent.getExtras().get(SMS_EXTRA_NAME);
for (Object message : messages) {
SmsMessage finalMessage = SmsMessage
.createFromPdu((byte[]) message);
receivedMessages.add(finalMessage);
}
return receivedMessages.toArray(new SmsMessage[0]);
}
}
我能够很好地读取传入的消息,但是假设从这里我想将消息转发到另一个电话号码并确保它已发送。我知道我可以执行 SmsManager.sendTextMessage()
但如何设置 PendingIntent
部分以通知短信是否已发送?
So this is my BroadcastReceiver
public class IncomingSMSListener extends BroadcastReceiver {
private static final String SMS_EXTRA_NAME = "pdus";
@Override
public void onReceive(Context context, Intent intent) {
SmsMessage[] messages = fetchSMSMessagesFromIntent(intent);
}
private SmsMessage[] fetchSMSMessagesFromIntent(Intent intent) {
ArrayList<SmsMessage> receivedMessages = new ArrayList<SmsMessage>();
Object[] messages = (Object[]) intent.getExtras().get(SMS_EXTRA_NAME);
for (Object message : messages) {
SmsMessage finalMessage = SmsMessage
.createFromPdu((byte[]) message);
receivedMessages.add(finalMessage);
}
return receivedMessages.toArray(new SmsMessage[0]);
}
}
I'm being able to read the incoming message just fine and all, but let's say from here I want to forward the message to another phone number and make sure it got sent. I know I can do SmsManager.sendTextMessage()
but how do I set up the PendingIntent
part to be notified whether the SMS got sent or not?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好吧,最终找到了解决方案。由于传递到 BroadCastReceiver 中的 onReceive() 方法的上下文不允许我注册其他 BroadcastReceiver 来侦听“消息发送”事件,因此我最终掌握了应用程序上下文并执行以下操作
: :
SENT_SMS_FLAG 只是一个静态字符串,唯一标识我刚刚发出的意图。我的 MessageSentListener 看起来像这样:
}
OK, ended up finding the solution in the end. Since the context passed in to the onReceive() method in the BroadCastReceiver doesn't let me register other BroadcastReceivers to listen for the "message sent" event, I ended up getting a grip of the app context and doing what follows:
In the BroadcastReceiver:
SENT_SMS_FLAG is simply a static string that uniquely identifies the intent I just made. My MessageSentListener looks like this:
}
如果其他人像我一样并试图找出如何在 Kotlin 中执行此操作,这里有一些代码可能会对您的任务有所帮助:
只需注意几件事:
这是代码(很大程度上改编自 美国海军学院网站):
If anyone else was like me and trying to find out how to do this in Kotlin, here's some code that might help in your quest:
Just a few things to note:
Here's the code (as heavily adapted from the US Naval Academy's site):