如何让我的应用响应来自特定号码的短信

how to get my app to respond to a SMS from a specific number

我正在尝试构建一个响应特定号码短信的应用程序,为了进行更多演示,我需要这样的代码:

 if(number == +232344322)
 {
  do something
  } else 
 {
  do nothing
   }

那么在 android 中最简单的方法是什么???

您需要创建一个 BroadcastReceiver 当短信是 received.In 时将被调用 BroadCastReceiverOnReceive 编写代码检索短信的数量发件人并比较号码并据此执行任务。

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中你需要添加:

  1. **<application> 标签内带有 intent-filter 的接收者

     <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>
    
  2. 权限:

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

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