当我的手机重新启动时,我尝试发送短信。我的代码在活动中工作,我可以在活动中获取交付报告。但是我将相同的代码放在广播接收器中,它不起作用。
try
{
String SENT = "SMS_SENT";
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(SENT), 0);
registerReceiver(new BroadcastReceiver()
{
@Override
public void onReceive(Context arg0, Intent arg1)
{
int resultCode = getResultCode();
switch (resultCode)
{
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS sent",Toast.LENGTH_LONG).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE: Toast.makeText(getBaseContext(), "Generic failure",Toast.LENGTH_LONG).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE: Toast.makeText(getBaseContext(), "No service",Toast.LENGTH_LONG).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU: Toast.makeText(getBaseContext(), "Null PDU",Toast.LENGTH_LONG).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF: Toast.makeText(getBaseContext(), "Radio off",Toast.LENGTH_LONG).show();
break;
}
}
}, new IntentFilter(SENT));
SmsManager smsMgr = SmsManager.getDefault();
smsMgr.sendTextMessage(address, null,"Send sms", sentPI, null);
}
catch (Exception e)
{
Toast.makeText(this, e.getMessage()+"!\n"+"Failed to send SMS", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
如何在广播接收器或服务中使用此代码?