android打开数据连接(目测最稳定方式)

想打开android数据连接,在网上搜到的方法是反射ITelephony,代码如下:

        //开启数据连接
        Class telephonyManagerClz=TelephonyManager.class;
        Method mGetITelephony=telephonyManagerClz.getDeclaredMethod("getITelephony");
        mGetITelephony.setAccessible(true);
        Object iTelephony = mGetITelephony.invoke(tm);
        Method mEnableDataConn=iTelephony.getClass().getDeclaredMethod("enableDataConnectivity");//关闭是 disableDataConnectivity
        mEnableDataConn.setAccessible(true);
        mEnableDataConn.invoke(iTelephony);

但这种方法行不通(三个手机没有一个成功)。首先,使用非公开的api具有很大的局限性,因为不同的手机厂商都会把google的原系统进行自定义,它们会保证公开的api的通用性,但非公 开的api就不一定了;另外这种方法需要MODIFY_PHONE_STATE权限,android2.3及以上的版本只有系统应用才能申请该权限(详情 参见stackoverflow上的这个问题How to grant MODIFY_PHONE_STATE permission for apps ran on Gingerbread),所以这个方法行不通。

可靠的方法是使用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方法的源码如下:

    /**
     * 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) {
        }
    }

这个方法是不可见的,所以需要使用反射。

转载于:https://my.oschina.net/wisedream/blog/198466

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值