开发者

Android:Receiving SMS from a specific number?

I am new to android and I am working on an application in which I can set the phone number from whom I receive开发者_运维技巧 SMS and only that SMS will be acknowledged by the application. Can any one help me please?


Here is a code snippet -

public class SMSApp extends IntentReceiver {

static final String ACTION =
        "android.provider.Telephony.SMS_RECEIVED";

public void onReceiveIntent(Context context, Intent intent) {
    if (intent.getAction().equals(ACTION)) {
        StringBuilder buf = new StringBuilder();
        Bundle bundle = intent.getExtras();
        if (bundle != null) {
            SmsMessage[] messages = Telephony.Sms.Intents.getMessagesFromIntent(intent);
            for (int i = 0; i < messages.length; i++) {
                SmsMessage message = messages[i];
                String phNum = message.getDisplayOriginatingAddress();
                if ("xxx-xxx-xxxx".equals(phNum))
                {// Do your thing }
            }
        }

    }
}

You will of course need to put a receiver and a permission in the manifest similar to -

<uses-permission id="android.permission.RECEIVE_SMS" />
<application>
    <receiver class="SMSApp">
        <intent-filter>
            <action android:value="android.provider.Telephony.SMS_RECEIVED" />
        </intent-filter>
    </receiver>
</application>


the above code is correct. to add on to it, remeber to add this.abortBroadcast() so that your default message app will not get the message from that particular number.for example:

    for (int i = 0; i &lt; messages.length; i++) {
            SmsMessage message = messages[i];
            String phNum = message.getOriginatingAddress();
            if (phNum.equals("000000")) {
               this.abortBroadcast();
               // do something
            } else {
               // do something else
            }

        }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜