定义一个广播接收器
public class SMSReceiver extends BroadcastReceiver {
private SmsManager smsManager; @Override
public void onReceive(Context arg0, Intent intent) { if(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")){ SharedPreferences sp = arg0.getSharedPreferences("MSG_SEND_RESULT", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit(); smsManager = SmsManager.getDefault(); Object[] pdus=(Object[])intent.getExtras().get("pdus"); SmsMessage[] message=new SmsMessage[pdus.length]; for(int i=0;i<pdus.length;i++){
message[i]=SmsMessage.createFromPdu((byte[])pdus[i]); String msgAddr = message[i].getDisplayOriginatingAddress();
String msgContent = message[i].getDisplayMessageBody(); //自动回复短信
String content = "";
int count = 0;
if(msgContent.trim().equals("1")){//android
content = "android";
smsManager.sendTextMessage(msgAddr, null, content, null, null);
count = sp.getInt("android", 0)+1;
editor.putInt("android", count);
editor.apply();
}else if(msgContent.trim().equals("2")){//ios
content = "ios";
smsManager.sendTextMessage(msgAddr, null, content, null, null);
count = sp.getInt("iphone", 0)+1;
editor.putInt("iphone", count);
editor.apply();
}
}
}
}
}
添加权限:
<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
注册receiver
<receiver android:name="com.auto.SMSReceiver">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>