note

SMSReceiver (BroadcastReceiver사용) 본문

Android/기본

SMSReceiver (BroadcastReceiver사용)

투한 2012. 1. 18. 12:11






생성시 Activity를 생성하지 않습니다


 


안에 클래스가 없는걸 확인할 수 있습니다




manifest.xml 확인



두개의 클래스 생성

NotificationMessage는 Activity를 상속합니다(extends Activity)

SMSReceiver 는BroadcastReceiver를 상속합니다(extends BroadcastReceiver)




Activity manifest.xml 등록방법은 이전게시물에 설명을 많이 했기 때문에 생략합니다(위에 Activity누르고 등록해주면됨)

SMSReceiver  리시버 등록합니다



추가가 된 모습




코드 모습



누르고 다시 add



Intent Filter



거기서 또 add



Action 



SMS_RECEIVED



저장






main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/text"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

</LinearLayout>


manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="kr.android.sms.receiver"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="10" />
    <uses-permission android:name="android.permission.RECEIVE_SMS"/>

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity android:name="NotificationMessage"></activity>
        <receiver android:name="SMSReceiver">
            <intent-filter>
                <action android:name="android.provider.Telephony.SMS_RECEIVED"/>
            </intent-filter>
        </receiver>
    </application>

</manifest>


NotificationMessage.java
package kr.android.sms.receiver;

import android.app.Activity;
import android.app.NotificationManager;
import android.os.Bundle;
import android.widget.TextView;

public class NotificationMessage extends Activity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.main);

		TextView text = (TextView) findViewById(R.id.text);

		NotificationManager manager = (NotificationManager) 
				getSystemService(NOTIFICATION_SERVICE);

		manager.cancel(1234);

		text.setText("메세지 정상 수신");
	}
}


SMSReceiver.java
package kr.android.sms.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;

public class SMSReceiver extends BroadcastReceiver {
	private static final int NOTIFY_ID = 1234;

	@Override
	public void onReceive(Context context, Intent intent) {
		Bundle bundle = intent.getExtras();
		SmsMessage[] smsMgs = null;
		String str = "";
		String address = "";
		if (bundle != null) {

			// PDU : sms 메세지의 산업 포맷
			Object[] pdus = (Object[]) bundle.get("pdus");

			// 가져온 Object(pdu)만큼 SmsMessage객체 생성
			smsMgs = new SmsMessage[pdus.length];
			
			for (int i = 0; i < smsMgs.length; i++) {
				//Object 배열 (pdu)에 담겨있는 메세지를 byte[]로 캐스팅하여 smsMessage에 담음
				smsMgs[i] = SmsMessage.createFromPdu((byte[]) (pdus[i]));

				// 전화번호 추출
				address += smsMgs[i].getOriginatingAddress();

				// 메세지 추출
				str += smsMgs[i].getMessageBody();
				str += "\n";
			}
			Toast.makeText(context, address + ":" + str, Toast.LENGTH_LONG)
			.show();

			// Notification status bar에 등록
			addNotificationStatusBar(context, address, str);
		}
	}

	public void addNotificationStatusBar(Context context, String address,
			String message) {

		// 1. NotificationManager 얻기
		NotificationManager nm = (NotificationManager) context
				.getSystemService(Context.NOTIFICATION_SERVICE);

		// 2. Notification 객체 생성
		Notification noti = new Notification(R.drawable.ic_launcher,
				address	+ " : " + message,
				System.currentTimeMillis());

		Intent i = new Intent(context, NotificationMessage.class);

		PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, i,
				0);

		noti.setLatestEventInfo(context, address, message, pendingIntent);

		nm.notify(NOTIFY_ID, noti);
	}
}


Uses Permission 지정해 줘야함




manifest.xml 접근 ->Permission ->  add





클릭




저장








실행 화면