1. 程式人生 > >Android中監聽手機來電及狀態

Android中監聽手機來電及狀態

在專案中,需要監聽手機來電和簡訊息。 手機來電沒有專門的廣播,但是Android中有關於電話狀態改變的廣播:android.intent.action.PHONE_STATE。 其中撥電話廣播:android.intent.action.NEW_OUTGOING_CALL 有新的簡訊息廣播:android.provider.Telephony.SMS_RECEIVED Android中對電話的管理類是:TelephonyManage。 通過TelephonyManage,可以通過gteXXX()獲得一系列的電話的狀態資訊,如SIM的相關資訊等。具體的可以看下原始碼。 Android中監聽手機來電不是通過廣播來實現的。在TelephonyManage中,有個listener方法:
/**
     * Registers a listener object to receive notification of changes
     * in specified telephony states.
     * <p>
     * To register a listener, pass a {@link PhoneStateListener}
     * and specify at least one telephony state of interest in
     * the events argument.
     *
     * At registration, and when a specified telephony state
     * changes, the telephony manager invokes the appropriate
     * callback method on the listener object and passes the
     * current (udpated) values.
     * <p>
     * To unregister a listener, pass the listener object and set the
     * events argument to
     * {@link PhoneStateListener#LISTEN_NONE LISTEN_NONE} (0).
     *
     * @param listener The {@link PhoneStateListener} object to register
     *                 (or unregister)
     * @param events The telephony state(s) of interest to the listener,
     *               as a bitwise-OR combination of {@link PhoneStateListener}
     *               LISTEN_ flags.
     */
    public void listen(PhoneStateListener listener, int events) {
        String pkgForDebug = mContext != null ? mContext.getPackageName() : "<unknown>";
        try {
            Boolean notifyNow = true;
            sRegistry.listen(pkgForDebug, listener.callback, events, notifyNow);
        } catch (RemoteException ex) {
            // system process dead
        } catch (NullPointerException ex) {
            // system process dead
        }
    }

監聽器:PhoneStateListener是一個單獨的類,有一系列的狀態改變函式。用來監聽來電狀態的改變需要實現函式: onCallStateChanged。後面主要以onCallStateChanged為線索。 回到listen中,sRegistry的定義是:
private static ITelephonyRegistry sRegistry;
if (sRegistry == null) {
            sRegistry = ITelephonyRegistry.Stub.asInterface(ServiceManager.getService(
                    "telephony.registry"));             //初始化
        }

而 ITelephonyRegistry的真正實現類是:TelephonyRegistry。 TelephonyRegistry中,關於listen如何呼叫到PhoneStateListener的onCallStateChanged方法:(只擷取onCallStateChanged方法
if ((events & PhoneStateListener.LISTEN_CALL_STATE) != 0) {
                        try {
                            r.callback.onCallStateChanged(mCallState, mCallIncomingNumber);
                        } catch (RemoteException ex) {
                            remove(r.binder);
                        }
                    }
即呼叫了PhoneStateListener的callback中的onCallStateChanged方法, PhoneStateListener的callback中:
 IPhoneStateListener callback = new IPhoneStateListener.Stub() {
       ......
        public void onCallStateChanged(int state, String incomingNumber) {
            Message.obtain(mHandler, LISTEN_CALL_STATE, state, 0, incomingNumber).sendToTarget();
        }
        ......
        
    };

PhoneStateListener的中有一個Handler,來進行了處理:
Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            //Rlog.d("TelephonyRegistry", "what=0x" + Integer.toHexString(msg.what) + " msg=" + msg);
            switch (msg.what) {
               ......             
              
                case LISTEN_CALL_STATE:
                    PhoneStateListener.this.onCallStateChanged(msg.arg1, (String)msg.obj);
                    break;
               
              ......                
               
            }
        }
    };

而在PhoneStateListener中,onCallStateChanged函式是沒有做任何事情,需要我們自己來實現自己需要做的事情。
 /**
     * Callback invoked when device call state changes.
     *
     * @see TelephonyManager#CALL_STATE_IDLE
     * @see TelephonyManager#CALL_STATE_RINGING
     * @see TelephonyManager#CALL_STATE_OFFHOOK
     */
    public void onCallStateChanged(int state, String incomingNumber) {
        // default implementation empty
    }

那麼我們就需要自己來實現這個方法:
// create a phone state listener
	PhoneStateListener phoneListener = new PhoneStateListener() {
		@Override
		public void onCallStateChanged(int state, String incomingNumber) {
			// TODO Auto-generated method stub
			switch (state) {
			case TelephonyManager.CALL_STATE_RINGING:
				
                                //自己需要實現的功能
                                Log.d("zmq","TelephonyManager.CALL_STATE_RINGING");
				break;
			case TelephonyManager.CALL_STATE_IDLE:
			case TelephonyManager.CALL_STATE_OFFHOOK:
				//自己需要實現的功能
				Log.d("zmq", "CALL_STATE_IDLE,CALL_STATE_OFFHOOK ");
				break;
			}
			super.onCallStateChanged(state, incomingNumber);
		}
	};

然後得到TelephonyManager的例項後,呼叫listen方法就可以啦。
private TelephonyManager telephonyManager;
telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
telephonyManager.listen(phoneListener, PhoneStateListener.LISTEN_CALL_STATE);

Enjoy~