cocos网络切换通知
androidJava代码添加类 NetBroadcastReceiver package com.xiaochan.majiang;
import java.util.ArrayList;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class NetBroadcastReceiver extends BroadcastReceiver {
private static String NET_CHANGE_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
@Override
public void onReceive(Context context,Intent intent) {
Log.v("NetBroadcastReceiver","onReceive");
if (intent.getAction().equals(NET_CHANGE_ACTION)) {
Log.v("NetBroadcastReceiver","net change");
Native.onNetChange();
}
}
}
入口文件AppActivity.java private ConnectionChangeReceiver myReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
// ...
// 监听连接状态
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
myReceiver = new NetBroadcastReceiver();
this.registerReceiver(myReceiver,filter);
}
@Override
protected void onDestroy() {
this.unregisterReceiver(myReceiver);
}
JNIJava 回调C++的函数 JNIEXPORT void JNICALL Java_com_xiaochan_majiang_Native_onNetChange(JNIEnv* env,jclass method,jstring param) { cocos2d::log("Java_com_xiaochan_majiang_Native_onNetChange"); }
资料Android实时监听网络状态(2) iOS- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
...
//开启网络状况的监听
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(reachabilityChanged:)
name: kReachabilityChangedNotification
object: nil];
// 获取访问指定站点的Reachability对象
// 把 hostReachable = [Reachability reachabilityWithHostname:@"www.google.com"];
// 改成 hostReachable=[Reachability reachabilityForInternetConnection];
// 就可以解决
self.reach = [Reachability reachabilityForInternetConnection];
// 让Reachability对象开启被监听状态
[self.reach startNotifier];
- (void)reachabilityChanged:(NSNotification *)note
{
NSLog(@"reachabilityChanged");
MissionWeiXin::Instance().onNetChange();
// // 通过通知对象获取被监听的Reachability对象
// Reachability *curReach = [note object];
// // 获取Reachability对象的网络状态
// NetworkStatus status = [curReach currentReachabilityStatus];
}
问题与解决官方kReachabilityChangedNotification获取网络变化通知不准确 // 把 hostReachable = [Reachability reachabilityWithHostname:@”www.google.com”]; 改成 hostReachable=[Reachability reachabilityForInternetConnection];就可以了, 资料kReachabilityChangedNotification 被多次调用 [ iOS ] 网络监听 - 通知 扩展android 下通知多次http://bbs.csdn.net/topics/390865539 这只是广播,不能只依靠这个来判断,还需要得到当前网络的状态来判断。 通过保存捕获到的状态,在事件改变通知中做判断即可。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |