3

当来电时,我想在我的应用程序中执行一些操作(暂停游戏)。但是读取手机状态不起作用。我已在清单中授予权限(READ_PHONE_STATE)。来电时什么也没有发生。谢谢。

TelephonyManager telephonyManager;
PhoneStateListener listener;
telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
*
*
*
listener = new PhoneStateListener() {
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {

        switch (state) {
        case TelephonyManager.CALL_STATE_IDLE:
            Toast.makeText(SudokuGameActivity.this, "IDLE", Toast.LENGTH_SHORT).show();
          break;
        case TelephonyManager.CALL_STATE_OFFHOOK:
         Toast.makeText(SudokuGameActivity.this, "OFF Hook", Toast.LENGTH_SHORT).show();
          break;
        case TelephonyManager.CALL_STATE_RINGING:
            Toast.makeText(SudokuGameActivity.this, "Ringing", Toast.LENGTH_SHORT).show();
            mpauseButton.performClick();
          break;
          }

        }
       };
4

2 回答 2

3

您是否写了以下行:

 telephonyManager.listen(listener,PhoneStateListener.LISTEN_CALL_STATE);
于 2012-01-05T09:28:57.757 回答
1

创建监听器后,您需要调用“public void listen (PhoneStateListener listener, int events)”来监听。

另外,你可以试试这个:创建一个广播接收器处理动作android.intent.action.PHONE_STATE

代码示例:

public class PhoneStateReceiver extends BroadcastReceiver {

private TelephonyManager manager;

@Override
public void onReceive(Context context, Intent intent) {
    if (manager == null) {
        manager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    }
    String action = intent.getAction();
    System.out.println(action);
    System.out.println("current phone state:" + manager.getCallState());
}

}

于 2012-01-05T09:26:59.937 回答