본문 바로가기
Android

[Android] 안드로이드 : 브로드캐스트 수신자

by 꿈나무 김땡땡 2019. 12. 10.

1. 브로드캐스트 수신자란? (Broadcast Receiver)

  • 브로드캐스팅 : 메시지를 여러 대상(여러 애플리케이션 구성 요소)에게 전달
  • 브로드캐스트 수신자 : 앱에서 SMS 메시지를 받고 싶다면 브로드캐스트 수신자를 만들어서 등록
  • New > 브로드캐스트 수신자 만들기 > AndroidManifest.xml 에 추가됨

 

2. 브로드캐스트의 구분

 (1) 인텐트와 브로드캐스트

  • 인텐트 : 인텐트를 이용해서 액티비티 실행시 포그라운드(Foreground)로 실행 되어 사용자에게 보여짐.
    인텐트를 받으면 onReceive() 메소드가 자동으로 호출 됨
  • 브로드캐스트 : 백그라운드(Background)로 동작하므로 사용자가 모름

  (2) 브로드캐스트의 구분

  • 일반 브로드캐스트 (sendBroadcase() 메소드로 호출 됨)
    : 비동기적으로 실행되며 모든 수신자는 순서 없이 실행 됨 (때로는 동시에 실행 됨) 
    효율적이나, 한 수신자의 처리 결과를 다른 수신자가 이용할 수 없고 중간에 취소 불가
  • 순차 브로드캐스트 (sendOrderedBroadcase() 메소드로 호출 됨) 
    : 한번에 하나의 수신자에만 전달 되므로 순서대로 실행 됨. 중간에 취소하면 수신자는 받지 못함
    수신자가 실행 되는 순서는 인텐트 필터의 속성으로 정할 수 있으며, 순서가 같으면 임의로 실행 됨

 

3. 브로드캐스트 수신자 예제

(1) App > New > Other > Broadcast Receiver > SmsReceicer.java : 브로드캐스트 수신자 만들기

public class SmsReceiver extends BroadcastReceiver {

    private static final String TAG = "SmsReceiver";
    // 날짜를 문자열로 변경
    private static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d(TAG, "onReceive() 호출됨.");

        Bundle bundle = intent.getExtras();
        SmsMessage[] messages = parseSmsMessage(bundle);

        if (messages.length > 0) {
            String sender = messages[0].getOriginatingAddress();
            Log.d(TAG, "sender : " + sender);

            String contents = messages[0].getMessageBody().toString();
            Log.d(TAG, "contents :" + contents);

            Date receiveDate = new Date(messages[0].getTimestampMillis());
            Log.d(TAG, "received date : " + receiveDate);

            sendToActivity(context, sender, contents, receiveDate);
        }

    }

    private void sendToActivity(Context context, String sender, String contents, Date receiveDate) {
        Intent intent = new Intent(context, SmsActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                        |Intent.FLAG_ACTIVITY_SINGLE_TOP
                        |Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("sender", sender);
        intent.putExtra("contents", contents);
        intent.putExtra("receiveDate", format.format(receiveDate));

        context.startActivity(intent);

    }

    private SmsMessage[] parseSmsMessage(Bundle bundle) {
        Object[] objs = (Object[]) bundle.get("pdus");
        SmsMessage[] messages = new SmsMessage[objs.length];

        for (int i=0; i<objs.length; i++) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                String format = bundle.getString("format");
                SmsMessage.createFromPdu((byte[])objs[i], format);
            } else if (messages[i] == null) {
                Log.e(TAG, "message is null");
                break;
            } else {
                messages[i] = SmsMessage.createFromPdu((byte[]) objs[i]);
            }
        }
        return messages;
    }
}

 

(2) AndroidManifest.xml

<receiver
            android:name=".SmsReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="android.provider.Telephony.SMS_RECEIVED" />
            </intent-filter>
</receiver>

 

(3) App > New > Activity > SmsActivity.java

public class SmsActivity extends AppCompatActivity {
    EditText editText;
    EditText editText2;
    EditText editText3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sms);

        editText = (EditText) findViewById(R.id.editText);
        editText2 = (EditText) findViewById(R.id.editText2);
        editText3 = (EditText) findViewById(R.id.editText3);

        Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        Intent passedIntent = getIntent();
        processCommand(passedIntent);
    }

    // Generate > Override Methods


    @Override
    protected void onNewIntent(Intent intent) {
        processCommand(intent);
        super.onNewIntent(intent);
    }

    private void processCommand(Intent intent){
        if (intent != null) {
            String sender = intent.getStringExtra("sender");
            String contents = intent.getStringExtra("contents");
            String receiveDate = intent.getStringExtra("receiveDate");

            editText.setText(sender);
            editText3.setText(contents);
            editText2.setText(receiveDate);
        }

    }
}

 

(4) activity_sms.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


    <EditText
        android:id="@+id/editText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginStart="12dp"
        android:layout_marginLeft="12dp"
        android:layout_marginTop="2dp"
        android:ems="10"
        android:hint="발신번호"
        android:inputType="textPersonName" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="48dp"
        android:text="확인" />

    <EditText
        android:id="@+id/editText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentBottom="true"
        android:layout_marginStart="21dp"
        android:layout_marginLeft="21dp"
        android:layout_marginBottom="102dp"
        android:ems="10"
        android:hint="수신시각"
        android:inputType="textPersonName" />

    <EditText
        android:id="@+id/editText3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginStart="15dp"
        android:layout_marginTop="72dp"
        android:ems="10"
        android:hint="내용"
        android:inputType="textPersonName" />
</RelativeLayout>

 

 

* 권한 허용 하기 위해 Gradle Scripts > build.gradle > targetSdkVersion 22로 변경

* 콜백 메소드 (Callback Methods) : 어떤 이벤트가 발생한 후 수행 될 함수

  > 출처 : https://victorydntmd.tistory.com/48

 

[JS] 콜백 함수 (Callback Function)

2019. 06. 02 수정 1. 콜백함수란? JS에서 콜백 함수는 너무나 중요한 개념입니다. Node.js 환경에서 프로그래밍 시 반드시 필요한 개념이기도 합니다. 웹 개발을 해보셨으면 jQuery를 한 번 쯤은 사용해보거나 보..

victorydntmd.tistory.com

 

댓글