I want to enable/disable the data connection programmatically. I've used the following code:
void enableInternet(boolean yes)
{
ConnectivityManager iMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
Method iMthd = null;
try {
iMthd = ConnectivityManager.class.getDeclaredMethod("setMobileDataEnabled", boolean.class);
} catch (Exception e) {
}
iMthd.setAccessible(false);
if(yes)
{
try {
iMthd.invoke(iMgr, true);
Toast.makeText(getApplicationContext(), "Data connection Enabled", Toast.LENGTH_SHORT).show();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
dataButton.setChecked(false);
Toast.makeText(getApplicationContext(), "IllegalArgumentException", Toast.LENGTH_SHORT).show();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(), "IllegalAccessException", Toast.LENGTH_SHORT).show();
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
dataButton.setChecked(false);
Toast.makeText(getApplicationContext(), "InvocationTargetException", Toast.LENGTH_SHORT).show();
}
}
else
{
try {
iMthd.invoke(iMgr, true);
Toast.makeText(getApplicationContext(), "Data connection Disabled", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
dataButton.setChecked(true);
Toast.makeText(getApplicationContext(), "Error Disabling Data connection", Toast.LENGTH_SHORT).show();
}
}
}
It's working without any errors in the emulator but, I'm getting "InvocationTargetException" when I try to run it on a real device. I'm using API level 8 to build the application.
This code sample should work for android phones running gingerbread and higher:
Dont forget to add this line to your manifest file
@riHaN JiTHiN your program works fine for 2.3 and above, But it needs a small change in 'else' statement:
the 'true' should be changed to 'false'