cocos2dx3.3 C++和Android的网络连接状态

JAVA中:

package org.cocos2dx.cpp;

import org.cocos2dx.lib.Cocos2dxActivity;

import android.annotation.TargetApi;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.view.WindowManager;


public class AppActivity extends Cocos2dxActivity {


	public native void setNetworkState(int state);
	@TargetApi(17)
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	// 获取网络状态
		
		System.out.println("============获取网络状态  01==========================");
			IntentFilter netstatefilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);

			System.out.println("============获取网络状态  02==========================");
			BroadcastReceiver netstatereceiver = new BroadcastReceiver() {
				@Override
				public void onReceive(Context context, Intent intent) {

					System.out.println("============获取网络状态  03==========================");
					ConnectivityManager manager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
					System.out.println("============获取网络状态  04==========================");
					manager.getActiveNetworkInfo();
					System.out.println("============获取网络状态  05==========================");
					boolean etherconn = false;
					boolean wificonn = false;
					boolean mobileconn = false;
					try {
						NetworkInfo etherinfo = manager.getNetworkInfo(ConnectivityManager.TYPE_ETHERNET);
						if (etherinfo.getState() == NetworkInfo.State.CONNECTED) 
							etherconn = true;
					} catch (Exception e) {
					}
					try {
						NetworkInfo wifiinfo = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
						if (wifiinfo.getState() == NetworkInfo.State.CONNECTED) 
							wificonn = true;
					}
					catch (Exception e) {
					}
					try {
						NetworkInfo mobileinfo = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
						if (mobileinfo.getState() == NetworkInfo.State.CONNECTED) 
							mobileconn = true;
					} catch (Exception e) {
					}
					
					int state = 0;
					if (etherconn)
						state = 1;
					else if (wificonn)
						state = 2;
					else if (mobileconn)
						state = 3;
					
					setNetworkState(state);
				}
			};
			registerReceiver(netstatereceiver, netstatefilter);
	}
}


AndroidManifest.xml文件中获取网络权限



C++中,java返回

int g_networkstate = 0; // 0 : disconnected		1 : ethernet	2 : wifi	3 : mobile


void cocos_android_app_init (JNIEnv* env, jobject thiz) {
    LOGD("cocos_android_app_init");
    AppDelegate *pAppDelegate = new AppDelegate();
}
#ifdef __cplusplus
extern "C" {
#endif

	JNIEXPORT void JNICALL Java_org_cocos2dx_cpp_AppActivity_setNetworkState(JNIEnv * env, jobject thiz, jint state)
	{
		log("=========Java_org_cocos2dx_cpp_AppActivity_setNetworkState============> state = %d", state);
		g_networkstate = state;
	}

#ifdef __cplusplus
}
#endif

声明:NetworkStatus.h

#ifndef __H_NETWORKSTATE_H__
#define __H_NETWORKSTATE_H__


#include "cocos2d.h"
class NetworkStatus
{
public:
	enum Status
	{
		DISCONNECT = 0,
		ETHERNET,
		WIFI,
		MOBILE
	};
public:
	NetworkStatus();
	~NetworkStatus();
	Status getStatus();
};


#endif //__H_NETWORKSTATE_H__

实现:NetworkStatus.cpp


#include "NetworkStatus.h"

#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
#include 
#include 
#pragma comment(lib,"Iphlpapi.lib")
#elif (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
#include 
#include 
extern int g_networkstate;
#endif


NetworkStatus::NetworkStatus()
{
}

NetworkStatus::~NetworkStatus()
{
}

NetworkStatus::Status NetworkStatus::getStatus()
{
	bool etherconn = false;
	bool wificonn = false;
	bool mobileconn = false;

#if CC_TARGET_PLATFORM == CC_PLATFORM_WIN32

	PIP_ADAPTER_ADDRESSES iaa = nullptr;
	ULONG len = sizeof(IP_ADAPTER_ADDRESSES);
	iaa = (PIP_ADAPTER_ADDRESSES)malloc(len);
	if (iaa == nullptr)
		return Status::DISCONNECT;

	if (GetAdaptersAddresses(AF_INET, GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER, nullptr, iaa, &len) == ERROR_BUFFER_OVERFLOW)
	{
		free(iaa);
		if (len < sizeof(IP_ADAPTER_ADDRESSES))
			return Status::DISCONNECT;
		iaa = (PIP_ADAPTER_ADDRESSES)malloc(len);
		if (iaa == nullptr)
			return Status::DISCONNECT;
		if (GetAdaptersAddresses(AF_INET, GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER, nullptr, iaa, &len) != NO_ERROR)
		{
			free(iaa);
			return Status::DISCONNECT;
		}
	}

	PIP_ADAPTER_ADDRESSES iaaitor = iaa;
	while (iaaitor != nullptr)
	{
		if (iaaitor->OperStatus == IF_OPER_STATUS::IfOperStatusUp)
		{
			PIP_ADAPTER_UNICAST_ADDRESS unicast = iaaitor->FirstUnicastAddress;
			if (unicast != NULL)
			{
				bool ipvalid = false;
				for (int i = 0; unicast != NULL; i++)
				{
					char * ip = inet_ntoa(((sockaddr_in *)(unicast->Address.lpSockaddr))->sin_addr);
					if (strcmp(ip, "0.0.0.0") != 0 && strcmp(ip, "127.0.0.1") != 0 && strncmp(ip, "169.254", 7) != 0)
					{
						ipvalid = true;
						break;
					}
					unicast = unicast->Next;
				}

				if (ipvalid)
				{
					switch (iaaitor->IfType)
					{
					case IF_TYPE_ETHERNET_CSMACD:
					case IF_TYPE_PPP:
						etherconn = true;
						break;
					case IF_TYPE_IEEE80211:
						wificonn = true;
						break;
					default:
						break;
					}
				}
			}
		}

		iaaitor = iaaitor->Next;
	}

	free(iaa);

#elif CC_TARGET_PLATFORM == CC_PLATFORM_MAC

#elif CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID

	if (g_networkstate == 1)
		etherconn = true;
	else if (g_networkstate == 2)
		wificonn = true;
	else if (g_networkstate == 3)
		mobileconn = true;

#elif CC_TARGET_PLATFORM == CC_PLATFORM_IOS

#endif

	Status result = Status::DISCONNECT;
	do
	{
		if (etherconn)
		{
			result = Status::ETHERNET;
			break;
		}

		if (wificonn)
		{
			result = Status::WIFI;
			break;
		}

		if (mobileconn)
		{
			result = Status::MOBILE;
			break;
		}
	} while (false);

	return result;
}



调用处:
导入头文件#include "NetworkStatus.h"

每秒调用一次

auto _netstatus_icon = Sprite::create();
	_netstatus_icon->setAnchorPoint(Vec2(0, 0));
	_netstatus_icon->setPosition(Vec2(visbleSize.width - 35 - 5, visbleSize.height - 32 - 5));
	addChild(_netstatus_icon);
	schedule([&, network, _netstatus_icon](float value){
		NetworkStatus::Status status = network->getStatus();
		switch (status){
		case NetworkStatus::Status::DISCONNECT:
			_netstatus_icon->setTexture("networkStatus/disconnect_icon.png");
			break;
		case NetworkStatus::Status::ETHERNET:
			_netstatus_icon->setTexture("networkStatus/eth_icon.png");
			break;
		case NetworkStatus::Status::WIFI:
			_netstatus_icon->setTexture("networkStatus/wifi_icon.png");
			break;
		case NetworkStatus::Status::MOBILE:
			_netstatus_icon->setTexture("networkStatus/3g_icon.png");
			break;
		}
	}, 1.0f, "arenamain_netstatus_timer");



你可能感兴趣的:(Cocos2dx)