情况:
我有一个Service
(也尝试过使用一个Activity
)在每次按钮单击时发送 SMS 消息。我 99.9% 确定该方法sendSMS(...)
只被调用一次。Toasts
在BroadcastReceiver
屏幕上的任何地方从几秒钟到几乎是挑衅地创建,直到应用程序被强制停止。"SMS Sent"
卡在屏幕上一段时间,短信发送成功。你可以看到Toast
一点点淡入和淡出。
难道我做错了什么?
奖金:
为什么BroadcastReceiver
with "SMS delivered"
status 没有得到任何响应?
这是我很久以前从教程中获取的非常通用的代码:
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
sendSMS("5555555","hello world");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
sendSMS("5555555","hello world");
return Service.START_STICKY;
}
// ---sends an SMS message to another device---
private void sendSMS(final String phoneNumber, final String message) {
String SENT = "SMS_SENT";
String DELIVERED = "SMS_DELIVERED";
PendingIntent sentPI = PendingIntent.getBroadcast(this.getApplicationContext(), 0, new Intent(
SENT), 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(this.getApplicationContext(), 0,
new Intent(DELIVERED), 0);
// ---when the SMS has been sent---
registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(context, "SMS sent",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(context, "SMS error: Generic failure",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(context, "SMS error: No service",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(context, "SMS error: Null PDU",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(context, "SMS error: Radio off",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(SENT));
// ---when the SMS has been delivered---
registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(context, "SMS delivered",
Toast.LENGTH_SHORT).show();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(context, "SMS not delivered",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(DELIVERED));
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
}
/编辑:修复了问题,您可以在此问题的评论中阅读