Reputation: 3248
I'm trying to make an app to both show the state of the network type (2G, 3G, or 4G), which I have done by using TelephonyManager, and also notify the user whenever the network type changes. This is the part I have problem in, how can I monitor the network type and get notified whenever it changes?
Upvotes: 2
Views: 3267
Reputation: 3248
After a while here is a working code:
under onCreate
:
TelephonyManager TelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
TelephonyMgr.listen(new TeleListener(),
PhoneStateListener.LISTEN_DATA_CONNECTION_STATE);
and as a class :
public class TeleListener extends PhoneStateListener {
public void onDataConnectionStateChanged (int state, int networkType){
super.onDataConnectionStateChanged(state, networkType);
//Whatever you wanna do
}
}
the method onDataConnectionStateChanged(int state, int networkType)
gets triggered when either networkstype(2G,3G,4G) changes or the connection state (Connecting, disconnecting etc) changes
Upvotes: 0
Reputation: 1912
You would need something like this: (Remember this will only work on Android 4.2+)
// It Only works on Android 4.2+
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
telephonyManager.listen(new PhoneStateListener(){
@Override
public void onCellInfoChanged(List<CellInfo> cellInfo) {
super.onCellInfoChanged(cellInfo);
for (CellInfo ci : cellInfo) {
if (ci instanceof CellInfoGsm) {
Log.d("TAG", "This has 2G");
} else if (ci instanceof CellInfoLte) {
Log.d("TAG", "This has 4G");
} else {
Log.d("TAG", "This has 3G");
}
}
}
}, PhoneStateListener.LISTEN_CELL_INFO);
You will also need the android.permission.READ_PHONE_STATE
permission in your manifest.
Upvotes: 0
Reputation: 419
You should find your answer here for network changes http://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html
EDIT for mobile networks check out this answer.https://stackoverflow.com/a/21721139/1898809
And this post : https://stackoverflow.com/a/17341777/1898809
Upvotes: 1