1.如何检查当前默认网络连接选项是否启用.
2.如何在用户选择时启用Wi-Fi / GPRS,或(如果用户选择GPRS,则禁用Wi-Fi – 如果GPRS只需要此选项)
还是有其他一些方法呢?
解决方法 尝试这个:ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);if (mWifi.isConnected()) //if wifi connected}ConnectivityManager connManager1 = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);NetworkInfo mMobile = connManager1.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);if (mMobile.isConnected()) { //if internet connected}
不要忘记在清单文件中添加这些权限;
androID.permission.CHANGE_WIFI_STATEandroID.permission.ACCESS_WIFI_STATEandroID.permission.UPDATE_DEVICE_STATSandroID.permission.CHANGE_NETWORK_STATEandroID.permission.ACCESS_NETWORK_STATEandroID.permission.MODIFY_PHONE_STATEandroID.permission.READ_PHONE_STATE
要启用或禁用Wifi,请使用mWiFi.setWifIEnabled(true | false)
要启用/禁用GPRS / 3G,请使用以下代码段.
voID turnData(boolean ON) throws Exception{if(bv == Build.VERSION_CODES.FROYO){ Log.i("version:","Found Froyo"); try{ Method dataConnSwitchmethod; Class telephonyManagerClass; Object ITelephonyStub; Class ITelephonyClass; TelephonyManager telephonyManager = (TelephonyManager) getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE); telephonyManagerClass = Class.forname(telephonyManager.getClass().getname()); Method getITelephonyMethod = telephonyManagerClass.getDeclaredMethod("getITelephony"); getITelephonyMethod.setAccessible(true); ITelephonyStub = getITelephonyMethod.invoke(telephonyManager); ITelephonyClass = Class.forname(ITelephonyStub.getClass().getname()); if (ON) { dataConnSwitchmethod = ITelephonyClass.getDeclaredMethod("enableDataConnectivity"); } else { dataConnSwitchmethod = ITelephonyClass.getDeclaredMethod("DisabledataConnectivity"); } dataConnSwitchmethod.setAccessible(true); dataConnSwitchmethod.invoke(ITelephonyStub); }catch(Exception e){ Log.e("Error:",e.toString()); }} else{ Log.i("version:","Found Gingerbread+"); final ConnectivityManager conman = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE); final Class conmanClass = Class.forname(conman.getClass().getname()); final FIEld iConnectivityManagerFIEld = conmanClass.getDeclaredFIEld("mService"); iConnectivityManagerFIEld.setAccessible(true); final Object iConnectivityManager = iConnectivityManagerFIEld.get(conman); final Class iConnectivityManagerClass = Class.forname(iConnectivityManager.getClass().getname()); final Method setMobileDataEnabledMethod = iConnectivityManagerClass.getDeclaredMethod("setMobileDataEnabled",Boolean.TYPE); setMobileDataEnabledMethod.setAccessible(true); setMobileDataEnabledMethod.invoke(iConnectivityManager,ON);}
}
总结以上是内存溢出为你收集整理的如何在Android应用程序中提供选择Wi-Fi或GPRS网络连接的选项全部内容,希望文章能够帮你解决如何在Android应用程序中提供选择Wi-Fi或GPRS网络连接的选项所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)