来电的电话号码不能正常工作

时间:2014-03-16 02:11:19

标签: java android

我有一个PhoneStateListener,用于在通话结束后打开应用。它工作正常,但我还需要获取来电号码,并使用incomingNumber字符串不起作用。这是我的代码:

public class PhoneStateManager extends PhoneStateListener{

    public static Boolean usingPhone = false;
    private MainActivity mainactivity;

    public PhoneStateManager(MainActivity main){
        mainactivity = main;
    }

    @Override
    public void onCallStateChanged(int state, String incomingNumber) {
        switch (state) {
        case TelephonyManager.CALL_STATE_IDLE:
            Log.d("DEBUG", "IDLE");
            if(usingPhone){
                Log.d("DEBUG", "number (PSM): " + incomingNumber);
                mainactivity.askQuestion(incomingNumber);
            }
            usingPhone = false;
            break;
        case TelephonyManager.CALL_STATE_OFFHOOK:
            Log.d("DEBUG", "OFFHOOK");
            usingPhone = true;
            break;
        case TelephonyManager.CALL_STATE_RINGING:
            Log.d("DEBUG", "RINGING");
            usingPhone = false;
            break;
        }
    }
}

LogCat语句在打电话时打印出来:

enter image description here

以下是我初始化PhoneStateManger的方法:

TelephonyManager tManager = (TelephonyManager) 
          getSystemService(Context.TELEPHONY_SERVICE);
PhoneStateManager listener = new PhoneStateManager(this);
tManager.listen(listener, PhoneStateManager.LISTEN_CALL_STATE);

我无法弄清楚为什么这个数字总是为空。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您必须将来电号码保存在响铃或摘机中

public class PhoneStateManager extends PhoneStateListener{

public static Boolean usingPhone = false;
private MainActivity mainactivity;
private String mIncomingNumber;

public PhoneStateManager(MainActivity main){
    mainactivity = main;
}

@Override
public void onCallStateChanged(int state, String incomingNumber) {
    switch (state) {
    case TelephonyManager.CALL_STATE_IDLE:
        Log.d("DEBUG", "IDLE");
        if(usingPhone){
            Log.d("DEBUG", "number (PSM): " + mIncomingNumber);
            mainactivity.askQuestion(mIncomingNumber);
        }
        usingPhone = false;
        break;
    case TelephonyManager.CALL_STATE_OFFHOOK:
        Log.d("DEBUG", "OFFHOOK");
        usingPhone = true;
        break;
    case TelephonyManager.CALL_STATE_RINGING:
        Log.d("DEBUG", "RINGING");
        mIncomingNumber = incomingNumber;
        usingPhone = false;
        break;
    }
}

}