是否可以读取传入的短信并仅回复特定或期望的号码

时间:2013-07-25 20:41:47

标签: android

是否可以读取传入的短信并仅回复特定或期望的号码。我想制作将在后台运行的应用......每当我发送带有我号码的短信时,它会自动回复我的XYZ信息

1 个答案:

答案 0 :(得分:4)

是的,这是可能的。您需要在应用中添加BroadcastReceiver,以拦截收到的短信,然后发送与您要查找的号码匹配的消息。

以下源代码:
BroadcastReceiver + SMS_RECEIVED
http://shreymalhotra.me/blog/tutorial/receive-sms-using-android-broadcastreceiver-inside-an-activity/

在AndroidManifest.xml中:

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

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

在一个名为SMSReceiver.java的新文件中:

public class SMSReceiver extends BroadcastReceiver 
{ 
    @Override 
    public void onReceive(Context context, Intent intent) { 
        // get SMS data, if bundle is null then there is no data so return
        Bundle extras = intent.getExtras();
        if (extras == null) return;

        // extract SMS data from bundle
        Object[] pdus = (Object[]) extras.get("pdus");
        for (int i = 0; i &lt; pdus.length; i++) {
            SmsMessage SMessage = SmsMessage.createFromPdu((byte[]) pdus[i]);
            String sender = SMessage.getOriginatingAddress();
            String body = SMessage.getMessageBody().toString();

            // if there's an SMS from this number then send
            if(sender.equals("+1800555555") {
                SmsManager smsManager = SmsManager.getDefault();
                smsManager.sendTextMessage(sender, null, "sms received", null, null);
            }
        }
    }
}