我有一个提醒应用程序,它会发送短信通知用户提醒时间已过。这效果很好。不过,我一直在测试当手机处于睡眠状态并错过提醒时会发生什么。
我正在使用
AlarmManager
设置闹钟以对应提醒时间。我的日志显示,当手机重新启动并尝试发送短信时,警报响起,但从未收到短信。
那么问题来了,有没有办法调试为什么短信不发送呢?
我当前的代码在发生警报事件时设置一个ContentObserver:
private void registerToListenForSentSMS()
{
MessageSentListener smsObeserver = new MessageSentListener(new Handler());
ContentResolver contentResolver = TheEveryOtherAlarmAppApplication.getAppContext().getContentResolver();
contentResolver.registerContentObserver(Uri.parse("content://sms"), true, smsObeserver);
}
MessageSentListener 收到发生某些 SMS 事件的通知:
public class MessageSentListener extends ContentObserver
{
public MessageSentListener(Handler handler)
{
super(handler);
}
@Override
public void onChange(boolean selfChange)
{
super.onChange(selfChange);
Log.d(Constants.ALARM_APP_LOG_TAG, "Something happend");
ContentResolver contentResolver = AlarmAppApplication.getAppContext().getContentResolver();
contentResolver.unregisterContentObserver(this);
}
}
但这可能是由与我的应用程序无关的短信事件引起的。无论如何,这并没有真正让我更接近解决方案 - 我想知道当什么都没有发生时出了什么问题!
如果未发送警报短信,我可以重新发送或使用其他通知方法,例如电子邮件等。
val TAG = "TRACK_SMS_STATUS"
private fun sendSMS(phoneNumber: String, message: String) {
val send = "SMS_SENT"
val delivered = "SMS_DELIVERED"
val sentPI = PendingIntent.getBroadcast(activity, 0,
Intent(send), PendingIntent.FLAG_IMMUTABLE)
val deliveredPI = PendingIntent.getBroadcast(activity, 0,
Intent(delivered), PendingIntent.FLAG_IMMUTABLE)
//---when the SMS has been sent---
registerReceiver(object : BroadcastReceiver() {
override fun onReceive(arg0: Context?, arg1: Intent?) {
val bundle: Bundle? = arg1?.extras
when (resultCode) {
AppCompatActivity.RESULT_OK -> {
Log.d(TAG, "SMS sent")
}
SmsManager.RESULT_ERROR_GENERIC_FAILURE -> {
Log.d(TAG, "Generic failure")
}
SmsManager.RESULT_ERROR_NO_SERVICE -> {
Log.d(TAG, "No service")
}
SmsManager.RESULT_ERROR_NULL_PDU -> {
Log.d(TAG, "Null PDU")
}
SmsManager.RESULT_ERROR_RADIO_OFF -> {
Log.d(TAG, "Radio off")
}
}
}
}, IntentFilter(send))
//---when the SMS has been delivered---
registerReceiver(object : BroadcastReceiver() {
override fun onReceive(arg0: Context?, arg1: Intent?) {
when (resultCode) {
AppCompatActivity.RESULT_OK -> {
Log.d(TAG, "SMS delivered")
}
AppCompatActivity.RESULT_CANCELED -> {
Log.d(TAG, "SMS not delivered")
}
}
}
}, IntentFilter(delivered))
val sms = SmsManager.getDefault()
sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI)
}