以编程方式在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来构建应用程序。
阿波罗的战车
相关分类