안드로이드/프로그래밍

프로세스 간 통신, Broadcast, 방송

에어버스 2015. 2. 24. 01:09

하나의 프로젝트에 MainActivity 와 서비스로 나눠 만들다 보니 서로 정보를 주고받기 위해 Broadcast 이용
Broadcast : 프로세스 간 통신
Handler : 프로세스 내 통신 (MainActivity 안에서 쓰레드 구현 시 MainActivity와 쓰레드 사이 통신)

1. 필터 등록 (메시지 처리기 등록) - Manifest.xml에서 해줘도 됨.
MainActivity.java 일부분

1
2
3
4
5
6
7
public void BR필터등록() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(_MSG_REQ_INFO); // 메시지 구분자 등록
        registerReceiver(mBR, filter); // 필터를 적용할 리시버(메시지 처리기) 등록
    }

 


2. 리시버 생성, 메시지 처리 구현 (Activity)
메시지 받으면 onReceive() 자동 호출됨. 메시지와 값(Extra이용)을 전달.
MainActivity.java 일부분

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
BroadcastReceiver mBR = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String strMsg = intent.getAction();
            if (_MSG_REQ_INFO.equals(strMsg)) {
                Intent intentService = new Intent();
                intentService.setAction(_MSG_PhoneExpressINFO);
                intentService.putExtra("_Num", m_번호);
                intentService.putExtra("_정규식", m_정규식);
                intentService.putExtra("_서버", m_서버);
                intentService.putExtra("_포트", m_포트); // 정보도 함께 전달
                sendBroadcast(intentService); // 메시지 전송
            }
        }
    };

 

A. 1번과 같음.
Service.java 일부분

1
2
3
4
5
6
 IntentFilter f = new IntentFilter();
        f.addAction(_SMS_RECEIVED); // SMS 이벤트
        f.addAction(_MSG_RECV_INFO); // 번호, 정규식 받기
        registerReceiver(SMSRecv, new IntentFilter(f));
 


B. 메시지 전달
Service.java 일부분

1
2
3
4
5
6
7
 void 번호_정규식요청() {
        Intent intent = new Intent();
        intent.setAction(_MSG_SEND_INFO);
        sendBroadcast(intent);
    }
 


B. MainActivity 에서 받은 메시지 처리
Service.java 일부분

1
2
3
4
5
6
7
8
9
10
11
12
BroadcastReceiver SMSRecv = new BroadcastReceiver(){
        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            String strAction = intent.getAction();
            if(_MSG_RECV_INFO.equals(strAction))
                정보받기(intent);
            else if(strAction == _SMS_RECEIVED){
                ...
            }
 


C. MainActivity 의 값을 받아온다. (2번 참조)
Service.java 일부분

1
2
3
4
5
6
7
8
 void 정보받기(Intent intent) {
        m_번호 = intent.getStringExtra("_Num");
        m_정규식 = intent.getStringExtra("_정규식");
        m_서버 = intent.getStringExtra("_서버");
        m_포트 =  Integer.parseInt(intent.getStringExtra("_포트"));
    }