Android中使用JAVA的反射机制控制数据连接

来源:互联网 发布:证券投资分析软件 编辑:程序博客网 时间:2024/05/20 01:10

使用ConnectivityManager,代码如下:

public static void setDataConnectionState(Context cxt, boolean state) {             ConnectivityManager connectivityManager = null;        Class connectivityManagerClz = null;        try {            connectivityManager = (ConnectivityManager) cxt                    .getSystemService("connectivity");            connectivityManagerClz = connectivityManager.getClass();            Method method = connectivityManagerClz.getMethod(                    "setMobileDataEnabled", new Class[] { boolean.class });            method.invoke(connectivityManager, state);        } catch (Exception e) {            e.printStackTrace();        }    }另ConnectivityManager的setMobileDataEnabled方法的源码如下:<pre name="code" class="java">    /**     * Sets the persisted value for enabling/disabling Mobile data.     *     * @param enabled Whether the mobile data connection should be     *            used or not.     * @hide     */    public void setMobileDataEnabled(boolean enabled) {        try {            mService.setMobileDataEnabled(enabled);        } catch (RemoteException e) {        }    }
这个方法是不可见的,所以需要使用反射。
总结:

1.首先要找到类名,就是你要反射函数所在的类

2.找到方法,用getMethod(...)注意里边的参数

2.抛出反射invoke方法


0 0
原创粉丝点击