如何从BroadcastReceiver发送短信并检查其状态?

时间:2011-08-15 02:58:41

标签: android sms broadcastreceiver android-pendingintent

所以这是我的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部分以通知是否发送了短信?

1 个答案:

答案 0 :(得分:6)

好的,最后找到了解决方案。由于传入BroadCastReceiver中的onReceive()方法的上下文不让我注册其他BroadcastReceivers来监听“message sent”事件,我最终得到了app上下文并执行以下操作:

在BroadcastReceiver中:

SmsManager smsManager = SmsManager.getDefault();
    Intent intent = new Intent(SENT_SMS_FLAG);
    PendingIntent sentIntent = PendingIntent.getBroadcast(context, 0,
            intent, 0);
    SMSForwarderApp.getAppContext().registerReceiver(
            new MessageSentListener(),
            new IntentFilter(SENT_SMS_FLAG));
    smsManager.sendTextMessage("Here goes the destination of the SMS", null,
            "Here goes the content of the SMS", sentIntent, null);

SENT_SMS_FLAG只是一个静态字符串,它唯一地标识我刚刚创建的意图。我的MessageSentListener看起来像这样:

public class MessageSentListener extends BroadcastReceiver{

@Override
public void onReceive(Context context, Intent intent) {
    int resultCode = this.getResultCode();
    boolean successfullySent = resultCode == Activity.RESULT_OK;
    //That boolean up there indicates the status of the message
    SMSForwarderApp.getAppContext().unregisterReceiver(this);
            //Notice how I get the app context again here and unregister this broadcast
            //receiver to clear it from the system since it won't be used again
}

}