我是Android的新手,我正在开发一个应用程序,我可以在其中设置我接收 SMS的电话号码,只有该应用程序才会确认该SMS。有人能帮帮我吗?
答案 0 :(得分:4)
以下是代码段 -
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 }
}
}
}
}
您当然需要在清单中放置接收者和权限,类似于 -
<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>
答案 1 :(得分:1)
上面的代码是正确的。要添加它,请记住添加this.abortBroadcast(),以便您的默认消息应用程序不会从该特定号码获取消息。例如:
for (int i = 0; i < messages.length; i++) {
SmsMessage message = messages[i];
String phNum = message.getOriginatingAddress();
if (phNum.equals("000000")) {
this.abortBroadcast();
// do something
} else {
// do something else
}
}