SMSを受信して特定の番号で送信するアプリを作成しています。BroadcastReceiver クラス内でステータス レポート (送信および配信) を取得したい。
BroadcastReceiver のコードは次のとおりです。
public class SmsReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
String messages = "";
String number = "6999999999";
if (extras != null)
{
// Get array data from SMS
Object[] smsExtra = (Object[]) extras.get("pdus"); // "pdus" is the key
for (int i=0; i<smsExtra.length; ++i)
{
// ------------------- SMS ------------------------------
SmsMessage sms = SmsMessage.createFromPdu((byte[])smsExtra[i]);
byte[] sms_body = null;
try {
sms_body = sms.getMessageBody().getBytes("UTF-8");
} catch (UnsupportedEncodingException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
String sms_address = sms.getOriginatingAddress();
sendSMS(number, "2", context);
}// end for
}// end if
}//end onReceive
配信レポートを取得するための以下のコード行を見つけました。registerReceiver でエラーが発生するため、BroadcastReceiver クラス内にそれらを含めることはできません。何か助けて??
//---sends an SMS message to another device---
private void sendSMS(String phoneNumber, String message,final Context context)
{
String SENT = "SMS_SENT";
String DELIVERED = "SMS_DELIVERED";
PendingIntent sentPI = PendingIntent.getBroadcast(context, 0, new Intent(SENT), 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(context, 0, new Intent(DELIVERED), 0);
//---when the SMS has been sent---
registerReceiver(new BroadcastReceiver(){
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode())
{
case Activity.RESULT_OK:
Toast.makeText(context, "SMS sent", Toast.LENGTH_SHORT).show();
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();
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;
}
}
}, new IntentFilter(SENT));
//---when the SMS has been delivered---
registerReceiver(new BroadcastReceiver(){
@Override
public void onReceive(Context arg0, Intent arg1) {
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);
}