Sunday, 29 September 2019

How to get updates of network type with PhoneStateListener in Android 7 and higher?

I have the following code that tells when the phone is connected to EDGE or UMTS network. It works on Android 6 (API 23) but when I test on Android 7 shows the network type only when I launch the app for first time, but there is no update when the phone changes from 2G to 3G and vice versa.

What is needed in order to make this code works updating the newtwork type in the moment that happens for Android 6 and 7+?

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    PhoneStateListener ConnectionStateListener = new PhoneStateListener() {

        @Override
        public void onDataConnectionStateChanged(int state, int networkType) {
            super.onDataConnectionStateChanged(state, networkType);
            String sState = "";

            switch (networkType) {
                case TelephonyManager.NETWORK_TYPE_EDGE:   sState = "EDGE (2G)";   break;
                case TelephonyManager.NETWORK_TYPE_UMTS:   sState = "UMTS (3G)";   break;                    
            }
            Toast.makeText(getApplicationContext(), sState, Toast.LENGTH_SHORT).show();
        }
    };
    telephonyManager.listen(ConnectionStateListener,PhoneStateListener.LISTEN_DATA_CONNECTION_STATE);
}

}

I've added to Manifest file the READ_PHONE_STATE permission as shown below.

<uses-permission android:name="android.permission.READ_PHONE_STATE" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>


from How to get updates of network type with PhoneStateListener in Android 7 and higher?

No comments:

Post a Comment