Ton
Ton

Reputation: 9776

Android mobile data on/off listener

I would like to know if there is a way to know when the user enables or disables the mobile data of the phone.I am NOT looking to see if my phone is currently connected by Mobile Network. I am trying to establish when the user enables / disables Data access over mobile network even if the wifi is connected at that moment.

The idea is to be able to know if the user will not have data once he/she leaves the house.

I tried with a broadcast like this:

    <receiver android:name=".MyReceiver">
        <intent-filter>
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
        </intent-filter>
    </receiver>

and it works. But the problem is that if the user disables or enables Data while connected to the Wifi then there isn't any event, so leaving the house will have the device disconnected.

I need to know this because I want to alert a parental that the kid left the house. I can only do this if the device is connected to internet. So if the wifi is lost I cannot tell the parent. The idea is to tell the parent that Mobile Data is off before leaving the house while there is wifi.

Upvotes: 1

Views: 2318

Answers (2)

mariosmant
mariosmant

Reputation: 454

It can be done with reflection as answered here How to tell if 'Mobile Network Data' is enabled or disabled (even when connected by WiFi)?

It will give tell you if the mobile data enabled or disabled.

As said there, it may not work on Lollipop+

Check here for the Lollipop tested way: Android API call to determine user setting "Data Enabled"

Edit: One way to achieve what your are looking for is to manually check the status of the mobile data as described above, periodically e.g. every minute or 10 seconds (if you want to be more effective).

Edit 2: You could also try ContentObserver as described here Listener for enable/disable mobile data (not connected or disconnnected) for a similar to "BroadcastReceiver" approach.

Upvotes: 0

Automatik
Automatik

Reputation: 337

You can extend the Broadcast Receiver in your class and then in the onReceive method:

    NetworkInfo networkInfo = conn.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    if(networkInfo!=null && networkInfo.isAvailable())
        //do something

Upvotes: -1

Related Questions