dinbrca
dinbrca

Reputation: 1107

Check when mobile data is connected using BroadcastReceiver | Android

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"/>

Upvotes: 0

Views: 2164

Answers (1)

Moliholy
Moliholy

Reputation: 539

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.

Upvotes: 3

Related Questions