0

I am trying to use PhoneStateListener to handle connection state changes. I've registered the listener inside onCreate method of a service. The overriden method onDataConnectionStateChanged(int state) of the listener is being called when I enable or disable wifi connection from the phone' settings, but in both cases the 'state' param is 0 and it always enters the first case of the switch. Here's my implementation of the method:

PhoneStateListener listener = new PhoneStateListener() { 
        @Override
        public void onDataConnectionStateChanged(int state) {
            super.onDataConnectionStateChanged(state);
            switch (state) {
                case TelephonyManager.DATA_DISCONNECTED:
                    Toast.makeText(LocationService.this, "Data connection lost!", Toast.LENGTH_LONG).show();
                    break;
                case TelephonyManager.DATA_CONNECTED:
                    Toast.makeText(LocationService.this, "Data connection available!", Toast.LENGTH_LONG).show();
                    break;
            }
        }
    };

The result is always a toast message saying: "Data connection lost!". I'm sure Im missing something simple here but I can't find out what the problem is.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Pancho C.
  • 133
  • 2
  • 7

1 Answers1

1

Old question, but the code you show is for "data", not for Wifi. I have the same code, and it's executed only when I connect with "LTE" (data)

private void registerDataListener(Context context) {

    listener = new PhoneStateListener() {
        @Override
        public void onDataConnectionStateChanged(int state) {
            switch (state) {
            case TelephonyManager.DATA_DISCONNECTED:
                Log.d(TAG, "Disconnected");
                break;
            case TelephonyManager.DATA_CONNECTED:
                Log.d(TAG, "Connected");
                break;
            case TelephonyManager.DATA_CONNECTING:
                Log.d(TAG, "Connecting");
                break;
            case TelephonyManager.DATA_SUSPENDED:
                Log.d(TAG, "Disconnecting");
                break;
            }
        }

    };
    telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    telephonyManager.listen(listener,PhoneStateListener.LISTEN_DATA_CONNECTION_STATE);
    Log.d(TAG, "Registering PhoneStateListener");

}

And don't forget to add permission in your manifest

<uses-permission android:name="android.permission.READ_PHONE_STATE" />
dalf
  • 582
  • 4
  • 11