adnroid受信したメールを傍受し、メールの内容に基づいて返信するメール

4966 ワード

ブロードキャスト受信機の定義
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>