如何在更改手机状态时打开布局?

时间:2015-06-01 13:06:25

标签: android telephonymanager phone-state-listener

我要做的是,在拨出电话和来电结束时,在屏幕上打开一个布局(仅当状态变为中间摘机时)。 每当我接听来电时以及每当其他人出席我的拨出电话时,我都希望在最后打开布局。

这是我写的代码。

MyPhoneStateHandler.java

public class MyPhoneStateHandler extends Activity {

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);

            startSignalLevelListener();
        }

        @Override
        protected void onPause() {
            // TODO Auto-generated method stub
            super.onPause();

            stopListening();
        }

        @Override
        protected void onResume() {
            // TODO Auto-generated method stub
            super.onResume();

            startSignalLevelListener();
        }

        @Override
        protected void onDestroy() {
            // TODO Auto-generated method stub
            stopListening();

            super.onDestroy();
        }

        private void stopListening(){
            TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
            tm.listen(photoStateListener, PhoneStateListener.LISTEN_NONE);
        }

        private void startSignalLevelListener(){
            TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
            int event = PhoneStateListener.LISTEN_CALL_STATE;

            tm.listen(photoStateListener, event);
        }

        private final PhoneStateListener photoStateListener = new PhoneStateListener(){

            @Override
            public void onCallStateChanged(int state, String incomingNumber)
            {
                String callState = "UNKNOWN";
                int tmpstate = 0;
                switch(state)
                {
                    case TelephonyManager.CALL_STATE_IDLE:      
                        callState = "IDLE";
                        if(tmpstate == 1){
                            setContentView(R.layout.cpl_after_call);
                            tmpstate = 0;
                        }
                        break;
                    case TelephonyManager.CALL_STATE_RINGING:   
                        callState = "Ringing (" + incomingNumber + ")";
                        tmpstate = 1;
                        break;
                    case TelephonyManager.CALL_STATE_OFFHOOK:   
                        callState = "Offhook"; 
                        break;
                 }

                Log.i("CLApp", "onCallStateChanged " + callState);

                super.onCallStateChanged(state, incomingNumber);
            }
        };
 }

我在通话期间收到一条消息,表明该应用已停止运行。

提前谢谢你。

1 个答案:

答案 0 :(得分:0)

当其他人接听电话时,您无法检测到状态转换。其余的状态转换将告诉您呼叫是否被丢弃。

如果您想检测其他人是否接听了呼叫,您需要分析并过滤掉Android生成的日志。这就是一些应用实现振动呼叫连接功能的方式。