这可以通过简单地注册您来实现,当您的消息发送PendingIntent
时BroadcastReceiver
通知您以及发送给预期收件人时通知您。只需按照以下步骤_
- 构建两个PendingIntent一个用于发送,另一个用于发送通知。
- 构建两个BroadcastReceiver。一个用于发送,另一个用于交付。
- 最后,通过 将这些 PendingIntent 注册到各自的BroadcastReceiver中
registerReceiver
,以便他们的 BroadcastReceiver得到通知并做必要的事情。
我已经建立了一个简单的类来完成我上面解释的工作。你可以通过这门课来全面了解它_
public class SendDeliverSMSActivity extends Activity {
Button btnSendSMS;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnSendSMS = (Button) findViewById(R.id.btnSendSMS);
btnSendSMS.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Your method that send sms
sendSMS("5556", "Hi You got a message!");
}
});
}
/**
* ---sends an SMS message to another device---
*
* @param phoneNumber
* @param message
*/
private void sendSMS(String phoneNumber, String message) {
// Intent Filter Tags for SMS SEND and DELIVER
String SENT = "SMS_SENT";
String DELIVERED = "SMS_DELIVERED";
// STEP-1___
// SEND PendingIntent
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(
SENT), 0);
// DELIVER PendingIntent
PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
new Intent(DELIVERED), 0);
// STEP-2___
// SEND BroadcastReceiver
BroadcastReceiver sendSMS = new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS sent",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getBaseContext(), "Generic failure",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getBaseContext(), "No service",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getBaseContext(), "Null PDU",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getBaseContext(), "Radio off",
Toast.LENGTH_SHORT).show();
break;
}
}
};
// DELIVERY BroadcastReceiver
BroadcastReceiver deliverSMS = new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS delivered",
Toast.LENGTH_SHORT).show();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(getBaseContext(), "SMS not delivered",
Toast.LENGTH_SHORT).show();
break;
}
}
};
// STEP-3___
// ---Notify when the SMS has been sent---
registerReceiver(sendSMS, new IntentFilter(SENT));
// ---Notify when the SMS has been delivered---
registerReceiver(deliverSMS, new IntentFilter(DELIVERED));
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
}
}
我希望这能帮到您!:)