我想以编程方式启用/禁用数据连接。我使用了以下代码:
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();
}
}
}
它在模拟器中没有任何错误地工作但是,我得到了#34; InvocationTargetException"当我尝试在真实设备上运行它时。 我使用API级别8来构建应用程序。
答案 0 :(得分:89)
此代码示例适用于运行gingerbread及更高版本的Android手机:
private void setMobileDataEnabled(Context context, boolean enabled) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
final ConnectivityManager conman = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
final Class conmanClass = Class.forName(conman.getClass().getName());
final Field connectivityManagerField = conmanClass.getDeclaredField("mService");
connectivityManagerField.setAccessible(true);
final Object connectivityManager = connectivityManagerField.get(conman);
final Class connectivityManagerClass = Class.forName(connectivityManager.getClass().getName());
final Method setMobileDataEnabledMethod = connectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
setMobileDataEnabledMethod.setAccessible(true);
setMobileDataEnabledMethod.invoke(connectivityManager, enabled);
}
别忘了将此行添加到您的清单文件
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
答案 1 :(得分:1)
@riHaN JiTHiN你的程序适用于2.3及以上版本,但它需要在“其他”中进行一些小改动。语句:
else
{
try {
iMthd.invoke(iMgr, true);
&#39; true&#39;应更改为“假”&#39;
iMthd.invoke(iMgr, false);