Chinese, Simplified
1. 概述
Android 上打开和关闭数据连接的API是隐藏的,即普通的apk没有权限来打开数据连接,本文提供用反射方法实现的例子,前提是apk需获得系统权限(有系统签名或者apk处在/system/priv-app/目录)。。
2. 参考代码
主要参考代码如下:
private void dataCtrlTest(){ Log.i(TAG,"dataCtrlTest start"); TelephonyManager telephonyManager = null; Class telephonyManagerClz = null; int isSimReady; boolean isDataEnabled=false; try { telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE); telephonyManagerClz = telephonyManager.getClass(); isSimReady = telephonyManager.getSimState(); Log.i(TAG,"sim state:"+isSimReady); //get api to set data Method setDataEnabled= telephonyManagerClz.getMethod( "setDataEnabled", new Class[] {boolean.class }); //get api to check data Method getDataEnabled= telephonyManagerClz.getMethod( "getDataEnabled", new Class[] {}); if(isSimReady==TelephonyManager.SIM_STATE_READY){ isDataEnabled = (boolean)getDataEnabled.invoke(telephonyManager); Log.i(TAG,"isDataEnabled :"+isDataEnabled); if(!isDataEnabled){ //enable data setDataEnabled.invoke(telephonyManager,true); }else{ //disable data setDataEnabled.invoke(telephonyManager,false); } isDataEnabled = (boolean)getDataEnabled.invoke(telephonyManager); Log.i(TAG,"isDataEnabled :"+isDataEnabled+" after setting"); } } catch (Exception e) { e.printStackTrace(); } Log.i(TAG,"dataCtrlTest end"); }
谢谢!