Network state change listener

979 Views Asked by At

I need to listen to change (connect/disconnect) of a network (mobile data in particular). I know the method using broadcast receiver and ConnectivityManager to know the type of connection.

But, in a broadcast receiver, an intent is received after the connection switches to the new network while I want to listen to the network which is being disconnected.

Why I want to do this?
I want to get the data stats for mobile data that is to say how much data has been transferred and received over 2g/3g/4g/LTE. I am using TrafficStats.getMobileRxBytes() to get the data received but opposite to what the documentation states this method returns zero when you are not connected to mobile data. Not only myself but many have have faced this issue as you can see here.

I know there is a workaround looking at the apps on Play Store giving the amount of data used on a daily basis.

Also, if I record data used for each second when the user is connected to Mobile data then I think it will not be too good for the battery.

Please, help me address this issue.

Thank You

0

There are 0 best solutions below