1. 利用繼承PhoneStateListener來實作當通話狀態為閒置、接起或響起時我們所要做的動作。

2. 由於我們需取得目前手機的通話狀態,因此必需在AndroidManifest.xml內新增一個讀取通話狀態的權限。

3. MainActivity.java

01.package org.me.android_callstate;
02.import android.app.Activity;
03.import android.content.Context;
04.import android.os.Bundle;
05.import android.telephony.PhoneStateListener;
06.import android.telephony.TelephonyManager;
07.import android.widget.Toast;
08. 
09.public class MainActivity extends Activity {
10. 
11.    @Override
12.    public void onCreate(Bundle icicle) {
13.        super.onCreate(icicle);
14.        setContentView(R.layout.main);
15.        //電話狀態的Listener
16.        MyPhoneStateListener myPhoneStateListener = new MyPhoneStateListener();
17.        //取得TelephonyManager
18.        TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
19.        //將電話狀態的Listener加到取得TelephonyManager
20.        telephonyManager.listen(myPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
21.    }
22. 
23.    public class MyPhoneStateListener extends PhoneStateListener {
24.        @Override
25.        public void onCallStateChanged(int state, String phoneNumber) {
26.            switch (state) {
27.                //電話狀態是閒置的
28.                case TelephonyManager.CALL_STATE_IDLE:
29.                    break;
30.                //電話狀態是接起的
31.                case TelephonyManager.CALL_STATE_OFFHOOK:
32.                    Toast.makeText(MainActivity.this"正接起電話…", Toast.LENGTH_LONG).show();
33.                    break;
34.                //電話狀態是響起的
35.                case TelephonyManager.CALL_STATE_RINGING:
36.                    Toast.makeText(MainActivity.this, phoneNumber + "正打電話來…", Toast.LENGTH_LONG).show();
37.                    break;
38.                default:
39.                    break;
40.            }
41.        }
42.    }
43.}


4. AndroidManifest.xml

01.<?xml version="1.0" encoding="UTF-8"?>
02.<manifest xmlns:android="http://schemas.android.com/apk/res/android"
03.     package="org.me.android_callstate">
04.    <application>
05.         <activity android:name=".MainActivity" android:label="MainActivity">
06.            <intent-filter>
07.                <action android:name="android.intent.action.MAIN"/>
08.                <category android:name="android.intent.category.LAUNCHER"/>
09.            </intent-filter>
10.        </activity>
11.    </application>
12.    <uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
13.</manifest>


4. 執行之後的畫面。

 

arrow
arrow
    全站熱搜

    小犬 發表在 痞客邦 留言(0) 人氣()