android开关gprs流量
2018-07-20 来源:open-open
一、需要权限:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" /> <uses-permission android:name="android.permission.MODIFY_PHONE_STATE" />
二、下面代码实现功能、如果gprs已经打开则先关闭再打开、否则直接打开、
package com.example.gprstoggle; import java.lang.reflect.Method; import android.app.Activity; import android.content.Context; import android.net.ConnectivityManager; import android.os.Bundle; public class MainActivity extends Activity { private ConnectivityManager mCM; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); } private void init() { mCM = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); gprsSetter(); finish(); } //打开或关闭GPRS private boolean gprsEnabled(boolean bEnable) { Object[] argObjects = null; boolean isOpen = this.gprsIsOpenMethod("getMobileDataEnabled"); if(isOpen == !bEnable) { setGprsEnabled("setMobileDataEnabled", bEnable); } return isOpen; } //打开或关闭GPRS private boolean gprsSetter() { Object[] argObjects = null; boolean isOpen = this.gprsIsOpenMethod("getMobileDataEnabled"); if(isOpen) { setGprsEnabled("setMobileDataEnabled", false); System.out.println("关闭"); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } setGprsEnabled("setMobileDataEnabled", true); System.out.println("开启"); }else{ setGprsEnabled("setMobileDataEnabled", true); System.out.println("开启"); } return isOpen; } //检测GPRS是否打开 private boolean gprsIsOpenMethod(String methodName) { Class cmClass = mCM.getClass(); Class[] argClasses = null; Object[] argObject = null; Boolean isOpen = false; try { Method method = cmClass.getMethod(methodName, argClasses); isOpen = (Boolean) method.invoke(mCM, argObject); } catch (Exception e) { e.printStackTrace(); } return isOpen; } //开启/关闭GPRS private void setGprsEnabled(String methodName, boolean isEnable) { Class cmClass = mCM.getClass(); Class[] argClasses = new Class[1]; argClasses[0] = boolean.class; try { Method method = cmClass.getMethod(methodName, argClasses); method.invoke(mCM, isEnable); } catch (Exception e) { e.printStackTrace(); } } }
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。
最新资讯
热门推荐