我正在开发一个在Android上发送短信的应用程序。
我还需要查找是否发送了消息。我已经尝试注册一个接收器来查找发送短信,如果我在短信发送之前不停止活动,它会很好地工作。但是如果我在发送消息之前关闭活动,则发送接收器将无法工作。
我该怎么办?
这就是我所做的(在我的活动中的一个函数内):
try
{
SmsManager smsManager = SmsManager.getDefault();
String to = "5556";
String body = "Test Message";
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(new BroadcastReceiver()
{
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode())
{
case Activity.RESULT_OK:
Toast.makeText(arg0, "SMS sent", Toast.LENGTH_LONG).show();
break;
default:
Toast.makeText(arg0, "Error", Toast.LENGTH_LONG).show();
break;
}
}
}, new IntentFilter(SENT));
registerReceiver(new BroadcastReceiver(){
@Override
public void onReceive(Context arg0, Intent arg1)
{
switch (getResultCode())
{
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS delivered", Toast.LENGTH_LONG).show();
break;
default:
Toast.makeText(getBaseContext(), "SMS not delivered", Toast.LENGTH_LONG).show();
break;
}
}
}, new IntentFilter(DELIVERED));
smsManager.sendTextMessage(to.getText().toString(), null, body.getText().toString(), sentPI, deliveredPI);
}
catch(Exception ex)
{
Toast.makeText(this, ex.getMessage(), Toast.LENGTH_LONG).show();
}
答案 0 :(得分:2)
您的BroadcastReceiver
已在Activity
动态注册,因此与Activity
生命周期相关联。要在Activity
未运行时接收广播,您需要在清单中静态注册BroadcastReceiver
课程。
请注意,您可以对已发送和已发送的广播使用相同的BroadcastReceiver
课程。