我该如何打开移动网络?

时间:2015-02-19 10:29:03

标签: android

我试图通过使用下面的代码打开MobileNetwork,但它不起作用,它会抛出** NoSuchMethodexception **。如何在没有NoSuchMethodException的情况下打开MOBILE NETWORK?

public void setMobileDataEnabled(boolean enabled,Context ctx) {
    try{
        final ConnectivityManager cm = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
        final Class conmanClass = Class.forName(cm.getClass().getName());
        final Field connectivityManagerField = conmanClass.getDeclaredField("mService");
        connectivityManagerField.setAccessible(true);
        final Object connectivityManager = connectivityManagerField.get(cm);      
        final Class connectivityManagerClass =  Class.forName(connectivityManager.getClass().getName());
        final Method setMobileDataEnabledMethod = connectivityManagerClass.getDeclaredMethod("setMobileDataEnabled",Boolean.TYPE);
        setMobileDataEnabledMethod.setAccessible(true);
        setMobileDataEnabledMethod.invoke(connectivityManager, enabled);
    }
    catch(Exception e){
        e.printStackTrace();
    }}

这是我添加的许可。

" android.permission.CHANGE_NETWORK_STATE"

1 个答案:

答案 0 :(得分:0)

访问WIFI状态:

WifiManager wifiManager ;
wifiManager  = (WifiManager)this.getSystemService(this.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);        //True - to enable WIFI connectivity .

用于访问DATA / 3G状态:

ConnectivityManager dataManager;
dataManager  = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
Method dataMtd = ConnectivityManager.class.getDeclaredMethod("setMobileDataEnabled", boolean.class);
dataMtd.setAccessible(true);
dataMtd.invoke(dataManager, true);        //True - to enable data connectivity .

现在您需要在Manifest文件中添加此权限:

<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>