在Android中阅读传入的短信

时间:2012-05-01 13:11:56

标签: android sms

我的应用程序中有一个BroadcastReceiver:

public class SMSReceiver extends BroadcastReceiver { 

   public void onCreate(){
        Log.i("APP","SMS Receiver started.");
   }

   @Override 
       public void onReceive(Context context, Intent intent) { 
           Log.i("APP", "SMS received.");
       }
   }

接收者:

<receiver class="SMSReceiver" android:name=".SMSReceiver" >
    <intent-filter>
        <action android:name="smsreceiver" android:value="android.provider.Telephony.SMS_RECEIVED" />
    </intent-filter>
</receiver>

<uses-permission android:name="android.permission.RECEIVE_SMS"/>

我从以下开始:

Intent SMS = new Intent(this, SMSReceiver.class);
sendBroadcast(SMS);

在主要活动中。

如何阅读邮件内容?感谢。

1 个答案:

答案 0 :(得分:1)

在你的主要节日中声明:

<receiver android:name=".SMSReceiver"> 
        <intent-filter android:priority="100"> 
            <action android:name=
                "android.provider.Telephony.SMS_RECEIVED" /> 
        </intent-filter> 
</receiver>

当您在清单中声明它时,无需从意图启动接收器,它会在传入消息到达时自动调用。

这是广播接收器的代码:

将此代码放入onRecieve方法

 if (!intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) 
                       return;          
                        bundle = intent.getExtras();

            if (bundle != null) {
                // ---retrieve the SMS message received---
                Object[] pdus = (Object[]) bundle.get("pdus");
                // Set<String> Bundle.keySet();
                msgs = new SmsMessage[pdus.length];
                // DeleteSMSFromInbox(context, msgs);
                for (int i = 0; i < msgs.length; i++) {

                    msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
                    ClsIncomingsmsNo = msgs[i].getOriginatingAddress();
                    System.out.println("ClsIncomingsmsNo" + ClsIncomingsmsNo);
                    msg = msgs[i].getMessageBody().toString();

}

}