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.
e.getMessage()
on theInvocationTargetException
? How about the enclosed exception? – Brittenybrittingham