본문 바로가기
프로그래밍

[안드로이드] SMS 수신하기

by A&co 2019. 7. 9.
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />

다음은 리버스 설정

<receiver android:name=".SMSBroadcast">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>

수신한 액션을 처리 하기 위한 브로트캐스트서버 파일

'SMSReceiver' class와 'SmsSender' class 생성

public class SmsReceiver extends BroadcastReceiver {

    public void onReceive(Context context, Intent intent) {
        Bundle bundle = intent.getExtras();
        SmsMessage[] msgs = null;
        String str = "";
        if (bundle != null)
        {
            Object[] pdus = (Object[]) bundle.get("pdus");
            msgs = new SmsMessage[pdus.length];
            for (int i=0; i<msgs.length; i++){
                msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
                str += "SMS from " + msgs[i].getOriginatingAddress();
                str += " :";
                str += msgs[i].getMessageBody().toString();
                str += "\n";
            }
            Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
        }
    }

}
public class SmsSender extends Activity {

    Button btnSendSMS;
    EditText txtPhoneNo;
    EditText txtMessage;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sms_send);

        btnSendSMS = (Button) findViewById(R.id.button);
        txtPhoneNo = (EditText) findViewById(R.id.phone);
        txtMessage = (EditText) findViewById(R.id.message);

                btnSendSMS.setOnClickListener(new View.OnClickListener()
                {
                    public void onClick(View v)
                    {
                        String phoneNo = txtPhoneNo.getText().toString();
                        String message = txtMessage.getText().toString();
                        if (phoneNo.length()>0 && message.length()>0)
                            sendSMS(phoneNo, message);
                        else
                            Toast.makeText(getBaseContext(),
                                    "Please enter both phone number and message.",
                                    Toast.LENGTH_SHORT).show();
                    }
                });
    }

    // SMS를 전송하는 과정을 모니터링하고 싶다면
    private void sendSMS(String phoneNumber, String message)
    {
        String SENT = "SMS_SENT";
        String DELIVERED = "SMS_DELIVERED";

        PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
                new Intent(SENT), 0);

        PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
                new Intent(DELIVERED), 0);

        //---when the SMS has been sent---
        registerReceiver(new BroadcastReceiver(){
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode())
                {
                    case Activity.RESULT_OK:
                        Toast.makeText(getBaseContext(), "SMS sent",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                        Toast.makeText(getBaseContext(), "Generic failure",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_NO_SERVICE:
                        Toast.makeText(getBaseContext(), "No service",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_NULL_PDU:
                        Toast.makeText(getBaseContext(), "Null PDU",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_RADIO_OFF:
                        Toast.makeText(getBaseContext(), "Radio off",
                                Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        }, new IntentFilter(SENT));

        //---when the SMS has been delivered---
        registerReceiver(new BroadcastReceiver(){
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode())
                {
                    case Activity.RESULT_OK:
                        Toast.makeText(getBaseContext(), "SMS delivered",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case Activity.RESULT_CANCELED:
                        Toast.makeText(getBaseContext(), "SMS not delivered",
                                Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        }, new IntentFilter(DELIVERED));

        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
    }

    // 모니터링 안하고 발송을 원한다면 아래 함수를 이용
    private void __sendSMS(String phoneNumber, String message)
    {
        PendingIntent pi = PendingIntent.getActivity(this, 0,
                new Intent(this, SmsSender.class), 0);
        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNumber, null, message, pi, null);
    }

}

다음은 레이아웃 부분이다. receive_sms.xml 생성

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="@+id/widget28"
    android:layout_width="fill_parent" android:layout_height="fill_parent"
    android:orientation="vertical" xmlns:android="http://schemas.android.com/apk/res/android">
    <TextView android:id="@+id/label1" android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:text="받는사람 전화번호"
        android:textSize="12sp">
    </TextView>
    <EditText android:id="@+id/phone" android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:textSize="18sp"
        android:phoneNumber="true">
    </EditText>
    <TextView android:id="@+id/label2" android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:text="메시지"
        android:textSize="12sp">
    </TextView>
    <EditText android:id="@+id/message" android:layout_width="fill_parent"
        android:layout_height="150px" android:gravity="top">
    </EditText>
    <Button android:id="@+id/button" android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:text="전송">
    </Button>
    </LinearLayout>

<연관글>

[안드로이드] SMS 전송하기