获取服务中的短信发送报告 [英] Get SMS Delivery Report with in service
问题描述
我尝试在我的手机重启时发送短信.我的代码在活动中工作,我可以在活动中获得交付报告.但我在广播接收器中放置了相同的代码,它不起作用.
I try to send sms when my mobile get rebooted.My code is working in activity,I can get the delivery report in activity.But I put the same code in Broadcastreceiver, It is not working.
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();
}
如何在广播接收器或服务中使用此代码?
How to use this code with in broadcastreceiver or in service?.
推荐答案
您不能在 BroadcastReceiver
中注册 BroadcastReceiver
,因为 BroadcastReceiver
可以寿命不长(仅在调用 onReceive()
期间.所以你需要做的是从你的 BroadcastReceiver
启动一个 Service
code> 并让它发送 SMS.您拥有的代码应该从 Service
工作.
You cannot register a BroadcastReceiver
in a BroadcastReceiver
because the BroadcastReceiver
does not live very long (only for the duration of the call to onReceive()
. So what you need to do is to start a Service
from your BroadcastReceiver
and have it send the SMS. The code you have should work from a Service
.
这篇关于获取服务中的短信发送报告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!