1

I used a Broadcast Receiver for listening the current wifi state. So it sets the current state to the text (connected, connecting, disabled,...) of a togglebutton (setText).

It works fine!

But now I want to do the same thing with the mobile data state..

So I used TelephonyManager to setup the receiver:

this.registerReceiver(this.DataStateChangedReceiver,
new IntentFilter(TelephonyManager.ACTION_PHONE_STATE_CHANGED));

Then I copied the code from the wifi receiver and edited it:

private BroadcastReceiver DataStateChangedReceiver
= new BroadcastReceiver()
{

    @Override
       public void onReceive(Context context, Intent intent) 
    {
        // TODO Auto-generated method stub


    int extraDataState = intent.getIntExtra(TelephonyManager.EXTRA_STATE ,
    TelephonyManager.DATA_DISCONNECTED);

    switch(extraDataState){
    case TelephonyManager.DATA_CONNECTED:
        data_toggle.setChecked(true);


     break;

    case TelephonyManager.DATA_DISCONNECTED:
        data_toggle.setChecked(false);


     break;

    case TelephonyManager.DATA_CONNECTING:
        data_toggle.setChecked(true);


     break;

    case TelephonyManager.DATA_SUSPENDED:
        data_toggle.setChecked(true);


     break;

    }
    }
};

The app starts but nothing happened with the toogleButton.. Is TelephonyManager the wrong way to do this? ConnectivityManager?

I want to set an onclicklistener to turn on / off the mobile data.

How to do this is the next question..

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • See http://stackoverflow.com/questions/3644144/how-to-disable-mobile-data-on-android for information on how to enable/disable mobile data – David Wasser Jul 19 '12 at 09:07

1 Answers1

-1

In my work I have used a trick with ACTION_SCREEN_ON and _OFF...... So, the trick is in such thing.... you create boolean variable in Receiver.class, and then change it when connection state is changed.... And then in service (or activity), where you get intent do what to do.....

    private boolean screenOff; 
@Override
public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
        screenOff = true;
    } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
        screenOff = false;
    }
    Intent i = new Intent(context, InternetService.class);
    i.putExtra("screen_state", screenOff);
    context.startService(i);
}
timonvlad
  • 1,046
  • 3
  • 13
  • 31
  • thank you, but I don't know if it helps me.. I'm searching for a method like the one for wifi. Is there nobody here who has written an example? – freibergisch Jul 19 '12 at 11:28