728x90

android.telephone.SmsManager class를 이용하여, API 코드 2줄로 SMS를 자동으로 보낼 수 있다.


SMS 메시지 보내는 코드

SmsManager smsManager = SmsManager.getDefault(); // Get the default instance of SmsManager

smsManager.sendTextMessage(phoneNumber, null, smsBody, null, null); // Send a text based SMS


MMS 메시지 보내는 코드

SmsManager sms = SmsManager.getDefault();
ArrayList<String> parts = sms.divideMessage(message);
sms.sendMultipartTextMessage(phoneNumber, null, parts, null, null); 


참고 : http://codetheory.in/android-sms/ 에 설명이 잘 나와있다.

private void SendSMS(String phonenumber, String message) {
    SmsManager smsManager = SmsManager.getDefault();
    if(smsManager == null) {
    return;
    }
    String sendTo = phonenumber;
    ArrayList<string> partMessage = smsManager.divideMessage(message);
    if(partMessage.size() > 1){
        Log.d("SMS", "Sending " + partMessage.size() + " parts");
    smsManager.sendMultipartTextMessage(sendTo, null, partMessage, null, null);
    } else {
    smsManager.sendTextMessage(sendTo, null, message, null, null);
    }


phoneNumber 를 다중(여러전화번호)으로 보낼 수 있는지 확인해보니 1건(한 전화번호)씩 보낸다.

SMS를 분할해서 보내는 코드에 대한 예제코드가 위 사이트에 잘 나와 있다.

이 방식을 이용하면 발송건수만큼 문자 보낸갯수가 생성된다.

문자를 보낸 개수를 지우는 방법을 강구해봐야겠다.


25개씩 잘라서 보내는 방법을 찾아보려고 코드를 구현한 건데 전혀 의미가 없는거 같다.

그냥 for문을 처음부터 끝까지 돌리면 될 일인듯.....


import java.util.Arrays;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class SendSMS extends Activity {

    Context mContext;
    EditText smsTextContext;
    String[] telNumArr;
    int mobileCnt;
    int selectedCnt;
    int limitCnt;
    int mod;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.send_sms);
       
        mContext = this;
        Intent intent = getIntent(); // 값을 받아온다.
        telNumArr = intent.getStringArrayExtra("mobileNOArr");
       
        smsTextContext = (EditText) findViewById(R.id.smsText);
        selectedCnt = telNumArr.length;
        limitCnt = 25;
        mod = (selectedCnt%limitCnt==0)?selectedCnt/limitCnt:selectedCnt/limitCnt+1;
       
    }   
   
    @SuppressLint("NewApi")
    public void sendSMS(View v){
        String smsText = smsTextContext.getText().toString();
       
        if (smsText.length()>0){
            String sumTelNum = "";
            for(int i=0;i < mod;i++){
                int startIndex = i*limitCnt;
                int endIndex = startIndex + limitCnt <= telNumArr.length ? startIndex + limitCnt : telNumArr.length;
                String[] subArray = Arrays.copyOfRange(telNumArr, startIndex, endIndex);
               System.out.println(i + "번째 서브배열"); 
                for (String telNum : subArray) {
                    System.out.println("telNum" + telNum);

                    telNum = telNum.replaceAll("[^0-9]", ""); // 숫자를 제외한 모든 문자 제거

                    if(telNum.length() == 0) continue;       
                    if(telNum.matches("(01[016789]{1})(\\d{3,4})(\\d{4})")){
                        telNum = telNum.replaceAll("(\\d{3})(\\d{3,4})(\\d{4})", "$1-$2-$3");
                    }
                    sumTelNum += telNum + ";";
                }
                   
                sendSMS(sumTelNum, smsText);               
               
                System.out.println("sumTelNum....." + sumTelNum);
                subArray = null;
                sumTelNum = "";
            }
        } else {
            Toast.makeText(this, "모두 입력해 주세요", Toast.LENGTH_SHORT).show();
        }
    }
   
    public void sendSMS(String smsNumber, String smsText){
        PendingIntent sentIntent = PendingIntent.getBroadcast(this, 0, new Intent("SMS_SENT_ACTION"), 0);
        PendingIntent deliveredIntent = PendingIntent.getBroadcast(this, 0, new Intent("SMS_DELIVERED_ACTION"), 0);
       
        // SMS가 발송될때 실행
        registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                switch(getResultCode()){
                    case Activity.RESULT_OK:
                        // 전송 성공
                        Toast.makeText(mContext, "전송 완료", Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                        // 전송 실패
                        Toast.makeText(mContext, "전송 실패", Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_NO_SERVICE:
                        // 서비스 지역 아님
                        Toast.makeText(mContext, "서비스 지역이 아닙니다", Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_RADIO_OFF:
                        // 무선 꺼짐
                        Toast.makeText(mContext, "휴대폰이 꺼져있습니다", Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_NULL_PDU:
                        // PDU 실패
                        Toast.makeText(mContext, "PDU Null", Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        }, new IntentFilter("SMS_SENT_ACTION"));
       
        // SMS가 도착했을때 실행
        registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                switch (getResultCode()){
                    case Activity.RESULT_OK:
                        // 도착 완료
                        Toast.makeText(mContext, "SMS 도착 완료", Toast.LENGTH_SHORT).show();
                        //finish();
                        break;
                    case Activity.RESULT_CANCELED:
                        // 도착 안됨
                        Toast.makeText(mContext, "SMS 도착 실패", Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        }, new IntentFilter("SMS_DELIVERED_ACTION"));
       
        SmsManager mSmsManager = SmsManager.getDefault();
        mSmsManager.sendTextMessage(smsNumber, null, smsText, sentIntent, deliveredIntent);
    }
}


----------------------------------------------------------------------

MMS 발송코드를  http://stackoverflow.com/questions/6580675/how-to-send-the-sms-more-than-160-character 에서 찾았는데 아직 테스트는 못해봤다. 테스트를 하면 글 내용을 다시 수정하련다.


SmsManager sm = SmsManager.getDefault();
ArrayList<String> parts =sm.divideMessage(LONG_TEXT);
int numParts = parts.size();

ArrayList<PendingIntent> sentIntents = new ArrayList<PendingIntent>();
ArrayList<PendingIntent> deliveryIntents = new ArrayList<PendingIntent>();

for (int i = 0; i < numParts; i++) {
sentIntents.add(PendingIntent.getBroadcast(getContext(), 0, mSendIntent, 0));
deliveryIntents.add(PendingIntent.getBroadcast(getContext(), 0, mDeliveryIntent, 0));
}

sm.sendMultiPartTextMessage(mDestAddr,null, parts, sentIntents, deliveryIntents)

블로그 이미지

Link2Me

,