前段时间写了个安卓蓝牙联机对战的游戏,写的也不怎么好,现在想写成个博客记录下

public class AppActivity extends Cocos2dxActivity {public Cocos2dxGLSurfaceView onCreateView() {Cocos2dxGLSurfaceView glSurfaceView = new Cocos2dxGLSurfaceView(this);glSurfaceView.setEGLConfigChooser(5, 6, 5, 0, 16, 8);return glSurfaceView;}// work for not static funcprivate static Cocos2dxActivity sContext = null;public static Context getContext() {return sContext;}//服务端和游戏端enum ServerOrCilent {NONE,  SERVICE,  CILENT  };//安卓调用 c++  向游戏中发送消息   private  native void StringFromJni(ArrayList<ChatMessage> str);public native int get();  public native void set(int i);  private native void SendTo(String msg);private native void SendMsgForServer(String msg);private native void SendMsgForClient(String msg);public static AppActivity instance;private BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();private BluetoothDevice device;  private ListView mListView;private ArrayList<ChatMessage> list = new ArrayList<ChatMessage>();private ServerOrCilent serverorcilent = ServerOrCilent.NONE;private BluetoothSocket socket;     // 客户端socketprivate ClientThread mClientThread; // 客户端运行线程private BluetoothServerSocket mserverSocket;     // 服务端socketprivate ServerThread mserverThread; // 服务端运行线程private ReadThread mreadThread;     // 读取流线程public static final String PROTOCOL_SCHEME_L2CAP = "btl2cap";public static final String PROTOCOL_SCHEME_RFCOMM = "btspp";public static final String PROTOCOL_SCHEME_BT_OBEX = "btgoep";public static final String PROTOCOL_SCHEME_TCP_OBEX = "tcpobex";private String address;//UUID可以看做一个端口号  private static final UUID MY_UUID =  UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");  public static Object getInstance(){if (instance==null){instance = new AppActivity();}return instance;}@Override  protected void onCreate(Bundle savedInstanceState) {  super.onCreate(savedInstanceState);    instance = this;Log.e("leeeee","AppActivity onCreate ------------------------");}  @Overrideprotected void onDestroy() {unregisterReceiver(mReceiver);super.onDestroy();}/*** 打开蓝牙*    返回0 : 没有蓝牙硬件或驱动* 返回1 : 打开了蓝牙* 返回2 : 以打开*/public  String openBlueToot(int type){if (mBluetoothAdapter == null) {          return "0";}      if(!mBluetoothAdapter.isEnabled()){ //请求用户开启  //Intent intent=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);  //startActivityForResult(intent, RESULT_FIRST_USER);  //使蓝牙设备可见,方便配对  //直接开启,不经过提示  mBluetoothAdapter.enable(); if(type == 1){Intent in=new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);  in.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);  startActivity(in); }     String name = mBluetoothAdapter.getName();serverorcilent = ServerOrCilent.SERVICE;return name;}else{if(type == 1){Intent in=new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);  in.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);  startActivity(in); }return mBluetoothAdapter.getName();}}/* 关闭蓝牙 */public void CloseBlueToot(){mBluetoothAdapter.disable();}/*** JNI* 扫描蓝牙*/public void findBuleToots(){Log.e("leeeee","findBuleToots ------------------------");serverorcilent = ServerOrCilent.CILENT;IntentFilter filterFound = new IntentFilter(BluetoothDevice.ACTION_FOUND);filterFound.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);filterFound.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);filterFound.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);filterFound.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);filterFound.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);  registerReceiver(mReceiver, filterFound);mBluetoothAdapter.startDiscovery();     }private final BroadcastReceiver mReceiver = new BroadcastReceiver() {@Overridepublic void onReceive(Context context, Intent intent) {            String action = intent.getAction();Log.e("leeeee","BroadcastReceiver  ------------------------");if (BluetoothDevice.ACTION_FOUND.equals(action)) {device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);Log.e("leeeee","BluetoothDevice addddd 2------------------------"+device.getName()+"_"+device.getAddress());if(device.getName()!= null){ChatMessage chmsg = new ChatMessage(device.getName(), device.getAddress());if(list.indexOf(chmsg) == -1)// 防止重复添加  {list.add(chmsg);StringFromJni(list);                             }       }                               } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {     Log.e("leeeee","BluetoothDevice nooooooooo 2------------------------");if(list.size() == 0){//list.add(new ChatMessage("no_device", "00"));   //StringFromJni(list);  }                                           }                    }};//搜索到所有的蓝牙设备后 选择一个服务器的地址public void chooseBlueDevice(String addr){Log.d("leeeee", "chooseBlueDevice 1..........................");  mBluetoothAdapter.cancelDiscovery(); //取消搜索//判断给定地址下的device是否已经配对BluetoothDevice device1 = mBluetoothAdapter.getRemoteDevice(addr);if(device1.getBondState() == BluetoothDevice.BOND_NONE){try{Method createBondMethod = BluetoothDevice.class  .getMethod("createBond");  Log.d("leeeee", "chooseBlueDevice 2..........................");  Boolean  returnValue = (Boolean) createBondMethod.invoke(device1);if(returnValue){        device = device1;address = addr;Log.e("leeeee","chooseBlueDevice success------------------------"+device1.getName());MyThread mt = new MyThread();mt.start();}else{Log.e("leeeee","chooseBlueDevice failed------------------------"+device1.getName());}}catch(Exception e){Log.e("leeeee","chooseBlueDevice bagin------------------------"+device1.getName());}} else if(device1.getBondState() == BluetoothDevice.BOND_BONDED){ //已经配对成功Log.d("leeeee", "已经配对成功 2..........................");  device = device1;address = addr;buildClientConnect();   }}private class MyThread extends Thread { public void run() {boolean istemp = true;while(istemp){Set<BluetoothDevice> set = mBluetoothAdapter.getBondedDevices();             for(BluetoothDevice dev : set){             if(dev.getAddress().equals(address)){                       istemp = false;buildClientConnect(); this.interrupt();break;}                          }}}}/*** JNI* 建立服务器 选择的一个用户*/public void buildServerConnect(){mserverThread = new ServerThread();  mserverThread.start();      }/*** JNI* 建立客户端 选择的一个用户*/public void buildClientConnect(){mClientThread = new ClientThread();mClientThread.start();}//开启服务器private class ServerThread extends Thread { public void run() {try {/* 创建一个蓝牙服务器 * 参数分别:服务器名称、UUID   */ mserverSocket = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(PROTOCOL_SCHEME_RFCOMM,MY_UUID);      Log.e("leeeee", "Server wait cilent connect*************************");/* 接受客户端的连接请求 */socket = mserverSocket.accept();Log.e("leeeee", "Server accept success***********************************");//启动接受数据mreadThread = new ReadThread();mreadThread.start();                } catch (IOException e) {e.printStackTrace();}}};// 开启客户端连接服务端private class ClientThread extends Thread {@Overridepublic void run() {if (device != null) {try {socket = device.createRfcommSocketToServiceRecord(MY_UUID);Log.e("leeeee", "Client loading***********************************");// 通过socket连接服务器,这是一个阻塞过程,直到连接建立或者连接失效if (!socket.isConnected()) {socket.connect();}Log.e("leeeee", "ClientThread success***********************************");sendMessageHandle("ClientThread_success_Server_BubbleGame");// 可以开启读数据线程mreadThread = new ReadThread();mreadThread.start();                   } catch (IOException e) {Log.e("leeeee", "ClientThread error***********************************"+e.getMessage());if(serverorcilent == ServerOrCilent.CILENT){SendMsgForClient("Connect_error");}else{SendMsgForServer("Connect_error");      }}}}}//发送数据public void sendMessageHandle(String msg) {      if (socket == null) {//Toast.makeText(mContext, "没有连接", Toast.LENGTH_SHORT).show();return;}try {    Log.e("Leeeeee","send... ------------------------"+msg);OutputStream os = socket.getOutputStream(); os.write(msg.getBytes());} catch (IOException e) {//如果断开连接 发送错误代码 -5if(serverorcilent == ServerOrCilent.CILENT){SendMsgForClient("State_-5");}else{SendMsgForServer("State_-5");        }e.printStackTrace();}          }// 通过socket获取InputStream流private class ReadThread extends Thread {@Overridepublic void run() {// TODO Auto-generated method stubbyte[] buffer = new byte[1024];int bytes;InputStream is = null;try {is = socket.getInputStream();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}while(true) {try {if ((bytes = is.read(buffer)) > 0) {byte[] data = new byte[bytes];for (int i = 0; i < data.length; i++) {data[i] = buffer[i];}String s = new String(data);Log.e("Leeeeee","read... ------------------------"+s);if(serverorcilent == ServerOrCilent.CILENT){if(s.equals("ClientThread_success")){SendTo("ClientThread_success");}else{SendMsgForClient(s);}     }else{if(s.equals("ClientThread_success")){SendTo("ClientThread_success");sendMessageHandle("ClientThread_success");}else{SendMsgForServer(s);}                                                                       }}} catch (IOException e) {try {is.close();} catch (IOException e1) {e1.printStackTrace();}break;}}}}/* 停止服务器 */private void shutdownServer() {new Thread() {public void run() {if(mserverThread != null){mserverThread.interrupt();mserverThread = null;}if(mreadThread != null){mreadThread.interrupt();mreadThread = null;}              try {                   if(socket != null){socket.close();socket = null;}if (mserverSocket != null){mserverSocket.close();/* 关闭服务器 */mserverSocket = null;}} catch (IOException e) {Log.e("server", "mserverSocket.close()", e);}};}.start();}/* 停止客户端连接 */private void shutdownClient() {new Thread() {public void run() {if(mClientThread!=null){mClientThread.interrupt();mClientThread= null;}if(mreadThread != null){mreadThread.interrupt();mreadThread = null;}//modify begin ---------if (mBluetoothAdapter != null && mBluetoothAdapter.isDiscovering()) {mBluetoothAdapter.cancelDiscovery();}//modify end ---------if (socket != null) {try {socket.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}socket = null;}};}.start();}
}
// 消息体
public class ChatMessage {private String name;private String address;public ChatMessage(String name, String address) {this.name = name;this.address = address;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getAddress() {return address;}public void setAddress(String address) {this.address = address;}
}

安卓中蓝牙对战游戏 (cocos2d-x 调用)相关推荐

  1. java蓝牙对战游戏_Java 蓝牙五子棋对战

    鉴于j2me的手机版蓝牙对战五子棋,包括完整源代码,资源资料齐全,特别希望入门者或高手参照,它导出的Jar资料也在压缩包内,如果你有模拟机的话,能够直接运行.效果如上. Java 蓝牙五子棋对战源代码 ...

  2. 尚硅谷_springcloud(2020新版) 下载_异界删除浓缩怎么得|原创下载异界仙战游戏一次搞定 异界仙战安卓下载地址最新版整理...

    这些天异界仙战游戏进行了一些晋级,不少粉丝都在座等妙手游田小妹发布最新的异界仙战下载地点,究竟结果正在线更新容易卡顿,而网上提供的所谓的"异界仙战民间最新版下载地点"也常常碰着不 ...

  3. iOS简易蓝牙对战五子棋游戏设计思路之一——核心蓝牙通讯类的设计

    iOS简易蓝牙对战五子棋游戏设计思路之一--核心蓝牙通讯类的设计 一.引言 本系列博客将系统的介绍一款蓝牙对战五子棋的开发思路与过程,其中的核心部分有两个,一部分是蓝牙通讯中对战双方信息交互框架的设计 ...

  4. iOS简易蓝牙对战五子棋游戏设计思路之二——核心棋盘逻辑与胜负判定算法

    2019独角兽企业重金招聘Python工程师标准>>> iOS简易蓝牙对战五子棋游戏设计思路之二--核心棋盘逻辑与胜负判定算法 一.引言 上一篇博客我们介绍了在开发一款蓝牙对战五子棋 ...

  5. android 蓝牙游戏下载,安卓手机蓝牙弹窗

    安卓手机蓝牙弹窗是一款非常实用的设置软件,界面简单明了,操作十分容易,在这款软件中有超多的功能系统,用户可以在上面随时查看电量使用情况,还能根据自己的喜好设置功能控制,还在等什么,感兴趣的小伙伴们赶紧 ...

  6. 基于安卓app开发项目(在线数独对战游戏平台)的毕业设计(附源码)

    大家好!我是职场程序猿,感谢您阅读本文,欢迎一键三连哦. 基于安卓app开发项目(在线数独对战游戏平台)的毕业设计 目录 一.项目简介 二.系统核心功能模块部分截图 2.1用户登陆的设计与实现 2.2 ...

  7. v4跨界战显示服务器维护中,V4跨界战手游预约-V4跨界战游戏首发预约_第一手游网...

    V4跨界战是一款非常震撼的动作射击冒险游戏,超级华丽的视觉冲击将在这里向您展示这个世界的战斗方式,各种超酷装备和武器的效果会让你享受一场非常精彩的战斗,一个充满魔力的世界吸引着你,每一次冒险都是难忘的 ...

  8. 以太联盟 基于区块链技术的角色扮演对战游戏

    以太联盟 是一款基于区块链技术的角色扮演对战游戏.玩家可以通过召唤英雄来为自己战斗从而赢取以太币奖励.每个玩家至多可以派5名英雄_上场.游戏共有5大种族, 5个职业,彼此之间互相克制,另外不同英雄还拥 ...

  9. UUNITY3D插件InControl的简单使用_安卓端连接蓝牙手柄

    由于项目需要,要在安卓端连接蓝牙手柄,找了一个unity上专门用来处理手柄连接的插件InControl,网上找了一圈,教程都很不明确,花了一点时间研究了一下,顺便封装了一下,在这记录一下. InCon ...

最新文章

  1. dmol3给定关键字不在字典中_python中的数据结构与算法(2):字典与集合
  2. java-jwt这个库没用过吧?
  3. Nature:拟南芥微生物组功能研究0概述
  4. python3 %%time 表示执行单元格时间 时间指的是CPU时间
  5. python列表按照指定顺序排序-Python常见排序操作示例【字典、列表、指定元素等】...
  6. 移动界面设计点滴:工欲善其事,必先利其器[转]
  7. python list 元素位置_Python将list中某个元素移至末尾
  8. 济南2021高考成绩查询,@全体济南人:2021夏季高考时间公布!
  9. python实习生面试题_【实习】暑期实习之python笔试题(一)
  10. Xmind模板文档分享——生活计划(3)
  11. SlidingBall滚动效果集成问题解决经验
  12. c# Monitor
  13. win10删除右键菜单多余项
  14. 服务器svn自动同步,svn主备服务器实时同步
  15. 最新版 Whatsapp 官网下载安装
  16. hazelcast java_Hazelcast
  17. 单片机助手,STM32、杰发科技、定时器计算工具助手,CAN比特率计算助手
  18. 如何将iPhone升级到ios 14
  19. 后端获取不到axios.post提交的参数
  20. php获取网站截图,异步获取评论者网站截图

热门文章

  1. 网课题库接口高准确率
  2. Orbit Downloader 1.5.4多国语言版
  3. mc经常闪退是java有问题_【疑问】求大神回答,mc闪退,提供崩溃报告
  4. CC2540-BLE4.0 学历笔记1之串口体验
  5. matlab mat文件转fcf,Matlab的FDATool设计滤波器导出
  6. bootstrap select 用法
  7. pytorch学习(一)pytorch中的断点续训
  8. 【Mysql】EVENT 使用基础 - Create Event
  9. 高光谱成像技术 有效助力果蔬产品无损检测
  10. android 中右上角的数字BadgeView