Android - 如何使用广播接收器来读取短信?

时间:2012-08-28 02:08:21

标签: android sms broadcastreceiver

在我的android项目中,我需要在进入时检测和阅读短信,然后从另一个类调用一个函数。

如何将下面的代码放在一个类中并在清单中正确定义它。如果我把它放在另一个Java文件上,那么我不知道如何从另一个Java文件调用一个函数。 我尝试将此代码放在我的主类中,但在我的应用程序中,它只是崩溃了。

public class SMSReceiverActivity extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        // Parse the SMS.
        Bundle bundle = intent.getExtras();
        SmsMessage[] msgs = null;
        String str = "";
        if (bundle != null)
        {
            // Retrieve the SMS.
            Object[] pdus = (Object[]) bundle.get("pdus");
            msgs = new SmsMessage[pdus.length];
            for (int i=0; i<msgs.length; i++)
            {
                msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
                // In case of a particular App / Service.
                //if(msgs[i].getOriginatingAddress().equals("+91XXX"))
                //{
                //str += "SMS from " + msgs[i].getOriginatingAddress();
                //str += " :";
                str += msgs[i].getMessageBody().toString();
                str += "\n";
                //}
            }
            if (str != "") { // remove the last \n
                str = str.substring(0, str.length()-1);
            }

            Reusable_CodeActivity.alert(my_ViewActivity.this, "AAAAAAAAAAA");
            try {
                //my_ViewActivity.this.handle_incoming_message(str);
            } catch(Exception e) {

            }
        }
    }
}

2 个答案:

答案 0 :(得分:0)

您接收短信的代码是正确的。但是当您在Activity类中使用BroadCastReceiver时,您需要在onStop()方法中取消注册,如下所示。我认为这就是你的活动破碎的原因。

@Override
protected void onStop()
{
    unregisterReceiver(mReceiver);
    super.onStop();
}

答案 1 :(得分:0)

如果我正确理解您的问题,您希望接收广播(当短信到达时),而您的活动正在显示。

如果是这样的话,我找到了一个很好的模式来做这一段时间(不记得我从哪里得到它,很高兴给予原作者的信任)。

首先,创建一个界面:

public interface Receiver {
    public void onReceive(Context context, Intent intent);
}

现在创建一个BroadcastReceiver的子类,我们可以在运行时动态注册:

public class PortableReceiver extends BroadcastReceiver {
    private Receiver mReceiver;

    public void setReceiver(Receiver receiver) {
        mReceiver = receiver;
    }

    public Receiver getReceiver() {
        return mReceiver;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        if (mReceiver != null)
            mReceiver.onReceive(context, intent);
        else
            Log.w("PortableReceiver", "Dropping received Result");
    }
}

现在我们可以在activity类中使用PortableReceiver:

public class MyActivity implements Receiver {
    private PortableReceiver mReceiver;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mReceiver = new PortableReceiver();
        mReceiver.setReceiver(this);
    }

    @Override
    public void onResume() {
        super.onResume();

        // Register the receiver
        IntentFilter filter = new IntentFilter();
        filter.addAction("_my_intent_action"); //TODO: add actions to filter just as you would in your AndroidManifest
        registerReceiver(mReceiver, filter, null, null);
    }

    @Override
    public void onPause() {
        super.onPause();
        unregisterReceiver(mReceiver);
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        //TODO: Your code goes here!
    }
}

现在您的Activity类直接处理Broadcast,因此您可以访问它可用的所有功能。

请注意,如果您想启动来自BroadcastReceiver的活动,那就有点不同了。如果是这种情况,我建议您查看http://www.vogella.com/articles/AndroidServices/article.html#pre_broadcastreceiver