简体   繁体   中英

phone number from incoming call not working android

I have a PhoneStateListener that is used to open an app once a phone call is finished. It works fine, but I also need to get the incoming calls number, and using the incomingNumber string does not work. Here is my code:

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;
        }
    }
}

The LogCat statements print out this when a phone call takes place:

在此处输入图片说明

Here is how I initialize the PhoneStateManger:

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

I can't figure out why the number is always null. Any ideas?

You have to save the incomingNumber in ringing or offhook

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;
    }
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM