阅读最后一封来自手机收件箱的短信

时间:2016-11-19 10:39:28

标签: java android

这是我的brodcast接收器代码

 Bundle myBundle = intent.getExtras();
    SmsMessage [] messages = null;
    String strMessage = "";

    if (myBundle != null)
    {
        Object [] pdus = (Object[]) myBundle.get("pdus");
        messages = new SmsMessage[pdus.length];

        for (int i = 0; i < messages.length; i++)
        {
            messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
            strMessage += "SMS From: " + messages[i].getOriginatingAddress();
            strMessage += " : ";
            strMessage += messages[i].getMessageBody();
            strMessage += "\n";
        }

        Toast.makeText(context, strMessage, Toast.LENGTH_SHORT).show();
        Intent inten = new Intent(context, MainActivity.class);
        inten.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        inten .putExtra("strMessage", strMessage);
        context.startActivity(inten);

我在主要活动中得到的价值如下: -

Intent inten= getIntent();

String strMessage = inten.getStringExtra("strMessage");
Toast.makeText(getApplicationContext(),strMessage,Toast.LENGTH_LONG).show();

但是,获得空值,请指导我,因为我是新手。

1 个答案:

答案 0 :(得分:1)

您只需要BroadcastReceiver注册IntentFilter "android.provider.Telephony.SMS_RECEIVED"。然后你就可以从这个意图中得到一条收到的消息:

    try {
        Object[] messages = (Object[]) intent.getSerializableExtra("pdus");
        for (Object msg : messages) {
            byte[] bytes = (byte[]) msg;
            SmsMessage message = SmsMessage.createFromPdu(bytes);
            String messageBody = message.getDisplayMessageBody(); // this is your SMS message body
        } catch (Exception e) {
            //catch exception here
        }

您需要向<uses-permission android:name="android.permission.RECEIVE_SMS"/>添加AndroidManifest.xml并处理Runtime permissions for API > 23