以编程方式在android中启用/禁用数据连接我想以编程方式启用/禁用数据连接。我使用了以下代码: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();
}
}}它在模拟器中没有任何错误,但是,当我尝试在真实设备上运行它时,我得到“InvocationTargetException”。我正在使用API级别8来构建应用程序。
2 回答
阿波罗的战车
TA贡献1862条经验 获得超6个赞
@riHaN JiTHiN您的程序适用于2.3及以上版本,但它需要在'else'语句中进行一些小改动:
else { try { iMthd.invoke(iMgr, true);
'true'应该改为'false'
iMthd.invoke(iMgr, false);
- 2 回答
- 0 关注
- 401 浏览
添加回答
举报
0/150
提交
取消