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~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值