Enable/Disable Mobile Data (GPRS) using code

前端 未结 4 1607

I was having one solution for enabling and disabling data that was working good in API 8 and 10, but that code was not compatible with the ICS, I need a global solution, so

4条回答
  •  [愿得一人]
    2020-12-09 14:35

    private static boolean enableMobileData(Context context, boolean enable) {
        boolean bool = true;
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        try {
            Class[] arrayOfClass = new Class[1];
            arrayOfClass[0] = Boolean.TYPE;
            Method enableDataMethod = ConnectivityManager.class.getMethod("setMobileDataEnabled", arrayOfClass);
            DailySchedulerLog.v("Method enableDataMethod = %s", enableDataMethod.getName());
            Object[] arrayOfObject = new Object[1];
            arrayOfObject[0] = Boolean.valueOf(enable);
            enableDataMethod.invoke(cm, arrayOfObject);
            return bool;
        } catch (Exception localException) {
            //            while (true) {
            DailySchedulerLog.d("Exception !!!!!!!!! loops");
            return bool = false;
            //            }
        }
    }
    

    this snipcode works with my case. Plz, add permissions related to change network

提交回复
热议问题