달력

4

« 2024/4 »

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
2012. 5. 13. 20:41

안드로이드 - SMS전송 안드로이드 이야기2012. 5. 13. 20:41

728x90
반응형

이미 안드로이드사이드를 통해 한글 번역판이 공개되어 있지만 저와 같은 초보개발자를 위해 좀 더 간추려 보았습니다.

근데 정리하고나니 큰 차이는 없는듯..ㅋㅋ

해당 소스는 현재 작업중인 저의 4번째 어플 기능중 일부분으로써 이번에 작업하면서 리팩토링하셨다고 보면 됩니다.

일단 AndroidManifest.xml 파일에 "SEND_SMS / RECEIVE_SMS" 2가지 권한을 추가합니다.

* AndroidManifest.xml
- Permissions 을 추가하여 안드로이드에서 해당 기능을 이용할 수 있도록 정의
- Permissions 항목 정의 및 종류는 http://www.androes.com/66 를 참고하세요!!

<?xml version="1.0" encoding="utf-8"?>
< manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.androes.imhere"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">

<!-- Activity Definition -->
<activity android:name=".SmsSender" android:label="SMS Sender">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</intent-filter>
</activity>

<!-- SMS 수신부분 정의 -->
<receiver android:name=".SmsReceiver">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>

</application>

<uses-sdk android:minSdkVersion="7" />

<!-- SMS 관련 -->
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
< /manifest>


* sms_send.xml
- SMS 보내기 UI 정의

<?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>


* SmsSender.java
- Main Activity 파일로 실제 sms UI 및 처리를 담당
- 번호와 메세지가 정상적으로 입력되면 sendSMS(phoneNo, message)를 통해 처리
- 전송과정을 Toast를 통해 모니터링 하고 싶다면 sendSMS() 함수를, 원치 않으면 __sendSMS()를 이용하시면 됩니다.
- 다른 클래스들과는 다르게 SmsManager 클래스를 사용하는데 이클래스는 직접적으로 초기화 하지 않으므로
SmsManger 객체를 얻을수 있는 정적 메소드인 getDefault() 를 호출하여 사용하게 됩니다.
sendTextMessage() 메소드를 이용하여 PendingIntent 와 함께 SMS 메시지를 전송하게 됩니다.
PendingIntent 객체는 메시지를 전송한후에 다른 액티비티를 보여주기 위해서 사용됩니다.
모니터링을 하기위해 PendingIntent 와 함께 두개의 BroadcastReceiver 객체가 사용됩니다.

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

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


* SmsSender.java Full Source

package com.androes.imhere;

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.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

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);

<!-- Send Button Click Event -->
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);
}

}


* SmsReceiver.java
- SMS 메시지를 받을때 onCreate() 메소드가 호출 될 것입니다.
- SMS 메시지는 번들 객체를 통해 Intent 객체(onReceive() 메소드의 두번째 파라미터)에 포함되어 있습니다.
- 이 메시지는 PDU 포맷으로 Object array 에 저장되어있습니다.
- 이 메시지를 가져오기 위해서는, SmsMessage 클래스로부터 정적 메소드인 createFromPdu()를 사용합니다.
- SMS 메시지는 Toast 클래스를 사용하여 보여집니다.

package com.androes.imhere;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;

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();
}
}

}
728x90
반응형
:
Posted by mapagilove