我正在开发一个 Android 短信应用程序。我用来发送短信的以下代码。
public void sendSms(final String phoneNumber, final String message){
String SENT = "SMS_SENT";
String DELIVERED = "SMS_DELIVERED";
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
new Intent(SENT), 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
new Intent(DELIVERED),0);
//--- When the SMS has been sent --
sendBroadcastReceiver=new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS sent",
Toast.LENGTH_SHORT).show();
ContentValues values = new ContentValues();
values.put("address", phoneNumber);
values.put("body", message);
getContentResolver().insert(Uri.parse("content://sms/sent"), values);
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();
ContentValues values1 = new ContentValues();
values1.put("address", phoneNumber);
values1.put("body", message);
getContentResolver().insert(Uri.parse("content://sms/queued"), values1);
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;
default:
break;
}
context.unregisterReceiver(this);
}
};
SmsManager sms = SmsManager.getDefault();
registerReceiver(sendBroadcastReceiver , new IntentFilter(SENT));
sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
}
当我保持屏幕直到发送短信时它工作正常。它会将短信写入内容/短信/已发送或排队取决于发送的报告。但是如果我在发送短信时按下后退按钮。它将发送短信但不写入内容/短信/已发送或排队也不会取消注册广播也。
请帮我解决我的问题。