我有一个发送短信(通过AsyncTask)的服务。我需要借助BraodcaseReceiver捕获发送/接收状态。 由于某些原因,我无法从Receiver获取正确的resultCode。如果我在Service中实现onReceive,则resultCode始终为null。
不确定我做错了什么,所以问题是将消息从Broadcase Receiver类发送回后台服务的正确方法是什么?
背景:
该应用程序由一项活动组成,该活动只运行后台服务。在该服务中,我发送短信。
我不太擅长Android设计模式,但是从网上看到的情况来看,要获得短信状态的结果,我需要创建一个单独的类作为BraodcaseReceiver。这就是为什么我创建一个。该BroadcastReceiver应该获得已发送消息的状态,而我想要的是能够将该值传递给服务(此后从服务传递到活动)
所以我正在做的是:Aactivty-> Service-> SendSMS,然后在任务完成后,我想接收已发送短信的状态。
注意:我刚刚意识到我没有使用AsyncTask发送短信。我只想将服务用作发送sms消息的AsyncTasks的管理器,并且我不希望他们发送消息来阻止该服务。这是一个好的设计吗?
服务:
protected boolean sendSMS(String number) {
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);
registerReceiver(sendBroadcastReceiver, new IntentFilter(SENT));
registerReceiver(deliveryBroadcastReceiver, new IntentFilter(DELIVERED));
String destinationAddress = number;
String smsMessage = String.format("This is test");
String scAddress = null;
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(destinationAddress, scAddress, smsMessage, sentPI, deliveredPI);
return true;
}
BroadcastReceiver sendBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Integer resultCode = intent.getExtras().getInt("msg");
//resultCode is always null here
Log.d("Debug", "sendBroadcastReceiver code: "+ resultCode);
}
};
广播接收者:
public class SentReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent arg1) {
Integer resultcode = getResultCode();
//**for some reason when I define onReceive in Service class**
//**I don't get any debug message as if this code doesn't execute**
Log.d("Debug", "Code: "+ resultcode);
Intent intent = new Intent("SMS_SENT");
intent.putExtra("msg", resultcode);
context.sendBroadcast(intent);
}
}