CocosCreator系列——获取手机网络状态并实时监听切换状态

CocosCreator系列——获取手机网络状态并实时监听切换状态

基于CocosCreator2.2.1版本,新建一个hello world工程,然后打开HelloWorld.js脚本编辑代码:

onGetNetState() {
        var netWorkInfo = jsb.reflection.callStaticMethod("org/cocos2dx/javascript/AppActivity", "getNetWorkState", "()I")
        if (!netWorkInfo) {
            cc.log("当前无返回!!!!!!!!!!!!!!!!!!!!!!!!");
            return
        }
        if (netWorkInfo == 1) {
            this.netLab.string = "发生变化,移动网络";
        } else if (netWorkInfo == 2) {
            this.netLab.string = "发生变化,wifi网络";
        } else {
            this.netLab.string = "无网络";
        }

    }

然后在onLoad()里面调用

if (cc.sys.isNative && cc.sys.os == cc.sys.OS_ANDROID) {
            this.schedule(() => {
                this.onGetNetState();
            }, 3)
        }

接下来打开AppActivity.java编辑Java原生代码,首先声明当前AppActivity并初始化,声明用来返回数据的变量netState 和初始化NetworkStateBroadcastReceiver

    private static AppActivity app = null;
    public static int netState = -1;
    private static NetworkStateBroadcastReceiver broadcastReceiver = null;

然后写NetworkStateBroadcastReceiver类,继承BroadcastReceiver

public class NetworkStateBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equalsIgnoreCase(WifiManager.WIFI_STATE_CHANGED_ACTION)){
                wifiStateChange(context, intent);
            }else{
                networkChange(context);
            }
        }

        public void wifiStateChange(Context context, Intent intent){
            int wifi_state = intent.getIntExtra("wifi_state", 0);
            int level = Math.abs(((WifiManager)context.getSystemService(Context.WIFI_SERVICE)).getConnectionInfo().getRssi());
            Log.e("network", "wifi状态:" + wifi_state + "; wifi强度:" + level);
        }

        public void networkChange(Context context){
            ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = manager.getActiveNetworkInfo();
            if(networkInfo != null){
                int type = networkInfo.getType();
                switch (type) {
                    case ConnectivityManager.TYPE_MOBILE:
                        netState = 1;
                        Log.e("network", "手机网络");
                        break;
                    case ConnectivityManager.TYPE_WIFI:
                        netState = 2;
                        Log.e("network", "wifi网络");
                        break;
                }
            }else{
                Log.e("network", "没有网络");
            }
        }

    }

接下来在onCreate()里面为AppActivity赋值,并注册监听手机电量服务

	app = this;
	app.broadcastReceiver = new NetworkStateBroadcastReceiver();
	IntentFilter filter = new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE");
	filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
	registerReceiver(broadcastReceiver, filter);

下面该写一个用来返回js客户端的方法了,netState在NetworkStateBroadcastReceiver类里面根据网络状态切换来存储

    public static int getNetWorkState(){
        return netState;
    }

在onDestroy()里面注销服务

if(broadcastReceiver!=null){
            app.unregisterReceiver(broadcastReceiver);
        }

建议用Android studio打开项目,缺少哪个引用直接alt+enter引入相应的模块就行了
最后一步,检查AndroidManifest.xml里面有没有声明权限

	<uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>

大功告成!!!!!!!!!!!!!!!!!
其实懂了以后挺简单的,刚开始不懂安卓原生,网上找了好多安卓的教程,大部分都是老版本了,试了好多都不行,为了与时俱进,还是要多多学习,经常更新迭代啊!!!!!!!!!!!!!
O(∩_∩)O

补充说明:如果需要显示WiFi链接强度的话,可以再声明一个变量来存储,WiFi强度在wifiStateChange()方法里面,log里面有,level就是

你可能感兴趣的:(CocosCreator)