结束活动后PendingIntent无法正常工作

时间:2014-07-28 07:32:09

标签: android broadcastreceiver

我正在开发一个在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();
}

1 个答案:

答案 0 :(得分:2)

您的BroadcastReceiver已在Activity动态注册,因此与Activity生命周期相关联。要在Activity未运行时接收广播,您需要在清单中静态注册BroadcastReceiver课程。

请注意,您可以对已发送和已发送的广播使用相同的BroadcastReceiver课程。