Android 来电状态监听

  • 核心类:PhoneStateListener
public class TestActivity extends FragmentActivity {

    private PhoneCallStateListener mListener = new PhoneCallStateListener();
    
    @Override
    public void onCreate(Context context) {
        super.onCreate(context);
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        if (telephonyManager == null) {
			return;
		}
        mListener.setCallListener(new CallListener() {
            @Override
            public void onCallIDLE() {
            	// 电话闲置状态(eg:挂断)
            }

            @Override
            public void onCallRinging() {
            	// 来电状态
            }

            @Override
            public void onCallOffHook() {
				// 正在通话中
            }
        });
        telephonyManager.listen(mListener, PhoneStateListener.LISTEN_CALL_STATE);
    }



    /**
     * 来电状态监听
     */
    class PhoneCallStateListener extends PhoneStateListener {


        private CallListener mCallListener;

        public void setCallListener(CallListener callListener) {
            mCallListener = callListener;
        }

        @Override
        public void onCallStateChanged(int state, String phoneNumber) {
            switch (state) {
                // 电话状态闲置
                case TelephonyManager.CALL_STATE_IDLE:
                    mCallListener.onCallIDLE();
                    break;
                // 来电
                case TelephonyManager.CALL_STATE_RINGING:
                    mCallListener.onCallRinging();
                    break;
                // 接通
                case TelephonyManager.CALL_STATE_OFFHOOK:
                    mCallListener.onCallOffHook();
                    break;
                default:
            }
        }
    }

    /**
     * 来电状态监听回调
     */
    public interface CallListener{
        void onCallIDLE();
        void onCallRinging();
        void onCallOffHook();
    }
}

你可能感兴趣的:(Android,开发实践)