0

I would like to know how can I check when mobile data is connected using BroadcastReceiver.

Here's what I have so far:

    private BroadcastReceiver MobileDataStateChangedReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        int state = intent.getIntExtra(TelephonyManager.EXTRA_STATE,
                TelephonyManager.DATA_DISCONNECTED);

        if (state == TelephonyManager.DATA_CONNECTED) {
            mobileStatus.setText("Connected");
        } else if (state == TelephonyManager.DATA_DISCONNECTED) {
            mobileStatus.setText("Disconnected");
        }
    }
};

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

    mobileStatus = (TextView) this.findViewById(R.id.textView4);

    registerReceiver(MobileDataStateChangedReceiver, new IntentFilter(
            TelephonyManager.ACTION_PHONE_STATE_CHANGED));
}

What am I doing wrong in here?

I used the same concept on Wi-Fi checking and it worked great? I am using the permissions of:

<uses-permission android:name="android.permission.INTERNET"/>
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
dinbrca
  • 1,101
  • 1
  • 14
  • 30

1 Answers1

3

The TelephonyManager.ACTION_PHONE_STATE_CHANGED does not seem to work because as I could read in TelephonyManager class description it only fires with calls, but not with networks or mobile data. Instead of this, I suggest you try setting a listener. It would be something like this:

1) Get the service with TelephonyManager tm = (TelephonyManager)Context.getSystemService(Context.TELEPHONY_SERVICE)

2) Set a listener with tm.listen(myCustomPhoneStateListener, PhoneStateListener.LISTEN_DATA_CONNECTION_STATE);

3) Once you have the listener you will be able to send custom intents to your BroadcastReceiver, if you still want to do that.

José Molina
  • 529
  • 2
  • 7
  • Thank you very much.. it worked and after what u said I searched for PhoneStateListener.LISTEN_DATA_CONNECTION_STATE and also got this: http://stackoverflow.com/questions/6179906/how-can-i-receive-a-notification-when-the-device-loses-network-connectivity – dinbrca Jul 05 '13 at 22:44
  • You are welcome. I also was looking for something similar for my Android application in order to prevent long downloads :) – José Molina Jul 06 '13 at 00:23