PhoneStateListenerを使って着信イベントを取得する


今回は、「PhoneStaetListener」を使って「着信のイベント」を取得する方法を紹介します。
TelephonyManagerのlisten-Methodに「PhoneStateListener」を登録し、
「onCallStateChanged」をOverrideすることで、着信時のイベントを取得することができます。

続きで具体的な方法を紹介します。

手法を紹介する前に、少しだけ寄り道を。

エミュレーターでの着信の発生

エミュレーター使用環境でも電話の着信を起こす事ができます。

エミュレーターが立ち上がった状態で、DDMSの「Emulator Control」タブの
「Telephony Actions」の項目を利用します。

Incomming number (エミュに)着信のある電話番号
Phone 電話イベント
SMS SMSイベント
Message SMSの際に使用
Call エミュレータに電話をかける


TelephonyManagerの準備

TelephonyManagerを使って端末の状態を取得する
の項目に習い、getSystemServiceからTELEPHONY_SERVICEを取得します。

1
2
mTelephonyManager
        = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);

TelephonyManagerのlisten-Methodに「PhoneStateListener」を登録します。
#前後が逆転しますが、Listenerは後述。

1
2
mTelephonyManager.listen
        (mPhoneStateListener,PhoneStateListener.LISTEN_CALL_STATE);

PhoneStateListener

PhoneStateListenerの実体を書きます。
今回は、以下の様にTextViewを追加する様にサンプルを書きました。

イベント名 出力文字 起こるタイミング
CALL_STATE_RINGING 着信 電話番号 着信時
CALL_STATE_OFFHOOK 通話中 通話開始時
CALL_STATE_IDLE 待ち受け中 待ち受け状態への変化時
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
31
32
<pre>PhoneStateListener mPhoneStateListener = new PhoneStateListener() {
    @Override
    public void onCallStateChanged(int state, String number) {
        phoneCallEvent(state, number);
       }
   };
 
   private void phoneCallEvent(int state, String number){
    switch(state) {
        /* 各状態でTextViewを追加する */
        case TelephonyManager.CALL_STATE_RINGING:
            /* 着信 */
            TextView tv_ring = new TextView(this);
            tv_ring.setText("着信  " + number);
            lLayout.addView(tv_ring);
 
            break;
 
        case TelephonyManager.CALL_STATE_OFFHOOK:
            /* 通話 */
            TextView tv_offhook = new TextView(this);
            tv_offhook.setText("通話中" + number);
            lLayout.addView(tv_offhook);
            break;
 
        case TelephonyManager.CALL_STATE_IDLE:
            /* 待ち受け */
            TextView tv_idle = new TextView(this);
            tv_idle.setText("待ち受け状態" + number);
            lLayout.addView(tv_idle);
            break;
    };

実行結果

実行結果は以下の通り。
実行時

着信のみの時

着信/通話の時

3 Comments