toggle Mobile Net - Android Network

Android examples for Network:Network Status

Description

toggle Mobile Net

Demo Code


//package com.java2s;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import android.content.Context;

import android.net.ConnectivityManager;

public class Main {

    public static void toggleMobileNet(Context context, boolean enabled) {
        Class conmanClass;/*  w w w .  ja  va2  s.co m*/

        ConnectivityManager conman = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        try {
            conmanClass = Class.forName(conman.getClass().getName());
            Field iConnectivityManagerField = conmanClass
                    .getDeclaredField("mService");

            iConnectivityManagerField.setAccessible(true);

            Object iConnectivityManager = iConnectivityManagerField
                    .get(conman);

            Class iConnectivityManagerClass = Class
                    .forName(iConnectivityManager.getClass().getName());

            Method setMobileDataEnableMethod = iConnectivityManagerClass
                    .getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);

            setMobileDataEnableMethod.setAccessible(true);

            setMobileDataEnableMethod.invoke(iConnectivityManager, enabled);
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }
}

Related Tutorials