我正在尝试在AsyncTask中发送SMS表单。我需要检索发送和传递的结果,因此必须使用BroadcastReceiver。 问题是我无法将braodcaseReceiever中的resultCode发送回被调用的活动或服务(实际上,调用者是Service)。
我尝试使用onPostExecute而不是运气,所以我的问题是我应该在哪里使用广播接收器?
我的AsnycTask的代码如下:
private class SmsTask extends AsyncTask<String, Void, Integer> {
private Context mContext;
private Integer sentStatus = 100;
public SmsTask(Context conctext) {
mContext = conctext;
}
protected boolean sendSMS(String number) {
String SENT = "SMS_SENT";
String DELIVERED = "SMS_DELIVERED";
// Set pending intents to broadcast
PendingIntent sentPI = PendingIntent.getBroadcast(mContext, 0, new Intent(SENT), 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(mContext, 0, new Intent(DELIVERED), 0);
registerReceiver(new BroadcastReceiver(){
@Override
public void onReceive(Context arg0, Intent arg1) {
sentStatus = getResultCode();
switch (sentStatus)
{
case Activity.RESULT_OK:
Log.i("IMMM", "SMS sent");
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Log.i("IMMM", "Generic failure");
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Log.i("IMMM", "No service");
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Log.i("IMMM", "Generic failure");
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Log.i("IMMM", "Radio off");
break;
}
}
}, new IntentFilter(SENT));
registerReceiver(new BroadcastReceiver(){
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode())
{
case Activity.RESULT_OK:
Log.i("IMMM", "SMS delivered");
break;
case Activity.RESULT_CANCELED:
Log.i("IMMM", "SMS not delivered");
break;
}
}
}, new IntentFilter(DELIVERED));
String destinationAddress = number;
String smsMessage = String.format("This is test sent to %s", number);
String scAddress = null;
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(destinationAddress, scAddress, smsMessage, sentPI, deliveredPI);
return true;
}
@Override
protected Integer doInBackground(String... params) {
sendSMS(params[0]);
return null;
}
@Override
protected void onPostExecute(Integer result) {
//here obviously is not the right place, it's being called way before we get status of sent message.
//it's always showing the default value 100 define up.
Log.i("IMMM", "Sent Status: "+ sentStatus.toString());
}
@Override
protected void onPreExecute() {}
}