我正在尝试构建一个响应特定号码短信的应用,为了更多演示,我想要一个这样的代码:
if(number == +232344322)
{
do something
} else
{
do nothing
}
那么在android ???中最简单的方法是什么?
答案 0 :(得分:2)
您需要创建一个BroadcastReceiver
,当收到短信时会调用该OnReceive
。在BroadCastReceiver
的{{1}}中写入代码,检索短信发送者的号码并比较编号并执行基于此的任务。
public class ReceiveSMS extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
final Bundle bundle = intent.getExtras();
if (bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
String message = currentMessage.getDisplayMessageBody();
Log.v("ranjapp", phoneNumber + " " + message);
if (phoneNumber.equals("+91xxxxxx"))) {
//do something
}else{
//do nothing
}
}
}
}
}
在AndroidManifest.xml中,您需要添加:
** <application>
标记
<receiver
android:name=".ReceiveSMS"
android:exported="true"
android:permission="android.permission.BROADCAST_SMS">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
<action android:name="android.provider.Telephony.SMS_DELIVER" />
</intent-filter>
</receiver>
<强>许可:强>
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<uses-permission android:name="android.permission.READ_SMS"/>