Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Telephone manager to detect sim

Tags:

android

I am working on an Android auto-start app that's basically dependent on SIM card state. When my app auto starts I need it to check where the SIM card has been changed or not. After that I compare the current SIM with the past SIM by obtaining the shared preference. But the app returns a null pointer exception when getting the new SIM card's value.

I want to react of SIM states.

When I receive the SIM_STATE_READY state I want to get the new SIM state from telephone manager.

  telMgr = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
     int simState = telMgr.getSimState();
    
     switch (simState) 
    {
        case (TelephonyManager.SIM_STATE_ABSENT):
            System.out.println("*******************************************Sim State absent******************************");
            break;
        case (TelephonyManager.SIM_STATE_NETWORK_LOCKED): 
            System.out.println("*******************************************SIM_STATE_NETWORK_LOCKED******************************"+sim);
            break;
        
        case (TelephonyManager.SIM_STATE_PIN_REQUIRED): 
            System.out.println("*******************************************SIM_STATE_PIN_REQUIRED******************************"+sim);
        break;
        case (TelephonyManager.SIM_STATE_PUK_REQUIRED): 
            System.out.println("*******************************************SIM_STATE_PUK_REQUIRED******************************"+sim);
        break;
        case (TelephonyManager.SIM_STATE_UNKNOWN): 
            System.out.println("*******************************************SIM_STATE_UNKNOWN******************************"+sim);
        break;
        case (TelephonyManager.SIM_STATE_READY): 
        {
    
        }
    break;
    }
    default: break;
    }

I'm doing this but don't know how to listen for SIM the states I want when the SIM is ready so that I can then execute some code. When the device boots up it always returns "SIM_STATE_UNKNOWN" and causes program's execution got complete.

like image 805
vivek_Android Avatar asked Feb 08 '11 13:02

vivek_Android


1 Answers

If you want to react to a Sim change you need to set a listener:

final TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);

    tm.listen(new PhoneStateListener() {
        @Override
        public void onServiceStateChanged(ServiceState serviceState) {
            //Code in here executed on Sim State change
        }

        @Override
        public void onDataConnectionStateChanged(int state) {

        }
like image 194
Kevin Bradshaw Avatar answered Nov 15 '22 00:11

Kevin Bradshaw