1

该应用程序会监听来电,然后停止播放音乐。然后,我希望音乐在通话结束后重新开始。但是我遇到了一个问题,CALL_STATE_IDLE因为它在应用程序启动时被检测到,所以它的方法内的任何调用都会在应用程序启动时被调用。

我的代码如下所示:

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
   ...
    listenForIncomingCall();
   ...
   }
    private void listenForIncomingCall() {
    PhoneStateListener phoneStateListener = new PhoneStateListener() {
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            if (state == TelephonyManager.CALL_STATE_RINGING) {
                //Incoming call: Pause music
                //stop playing music
            } else if (state == TelephonyManager.CALL_STATE_IDLE) {
                //Not in call: Play music

            //a code placed here activates on app starts

            } else if (state == TelephonyManager.CALL_STATE_OFFHOOK) {
                //A call is dialing, active or on hold
            }
            super.onCallStateChanged(state, incomingNumber);
        }
    };
    TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
    if (mgr != null)

    {
        mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
    }
}

我怎样才能防止这种情况?如果不在,我该如何注册一些听众onCreate

4

1 回答 1

2

我找到了一个替代解决方案。随意使用它。如果有人有更好的,请随时与社区分享。

private void listenForIncomingCall() {
    PhoneStateListener phoneStateListener = new PhoneStateListener() {
        boolean toTrack = false; //to prevent triggering in onCreate

        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            if (state == TelephonyManager.CALL_STATE_RINGING) {
                //Incoming call: Pause music
                doSomething();
            } else if (state == TelephonyManager.CALL_STATE_IDLE) {
                //Not in call: Play music
                if (toTrack) {
                    doSomething();
                }
                toTrack = true;
            } else if (state == TelephonyManager.CALL_STATE_OFFHOOK) {
                //A call is dialing, active or on hold
                if (toTrack) {
                    doSomething();
                }
                toTrack = true;
            }
            super.onCallStateChanged(state, incomingNumber);
        }
    };
    TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
    if (mgr != null)

    {
        mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
    }
}
于 2012-12-10T15:00:46.727 回答