"Original" cocos2d-x3.9 Bluetooth development Bluetooth enabled

Source: Internet
Author: User

I first engaged in the development of Android, a lot of things are only know a little bit, but not how to practice, so this time to learn to do what they want to function, it may take a long time, but it is certainly worthwhile, useful words or where to say wrong please correct me.

I have my own Android and Windows stuff, so I can only temporarily engage Android.

There are a few key steps in Bluetooth development, and I step-by-step

1, first turn on Bluetooth

2. Search for available devices

3. Create a Bluetooth socket to get the input and output stream

4, reading and writing data

5. Disconnect Bluetooth off

Let me start with the first step, turn on Bluetooth, and turn on Bluetooth is a process required.

The process is this, click on the Open button after Lua->c++->java, waiting for user feedback, user feedback after the Java->c++->lua processing user Feedback

First of all to use Java first implementation of the Android Bluetooth function and user feedback after the callback processing, in the frameworks\cocos2d-x\cocos\platform\android\java\src\org\cocos2dx\ New Cocos2dxbluetooth.java in the Lib directory:

Cocos2dxbluetooth.java:

 PackageOrg.cocos2dx.lib;ImportAndroid.bluetooth.BluetoothAdapter;Importandroid.content.Intent;ImportAndroid.preference.PreferenceManager.OnActivityResultListener;ImportAndroid.util.Log;/*** Created by Smileyg on 2016/1/4.
* The reason Cocos2dxbluetooth implements the Onactivityresultlistener interface is that Startactivityforresult requires an activity object to be called, At Init, I passed the Cocos2dxactivity instance object in and called,
* The Onactivityresult function within the cocos2dxactivity will have a callback distribution for the object that implements the Onactivityresultlistener, which needs to be added to a collection before it needs to be distributed.
* That is, the following cocos2dxhelper.addonactivityresultlistener, the specific look at the code to know*/ Public classCocos2dxbluetoothImplementsonactivityresultlistener{Static Final intEnable_request_code = 1; Private StaticCocos2dxactivity sactivity =NULL; Private Static native voidOpenrequesthandler (Final Booleanisopened); Public voidinit (cocos2dxactivity activity) {sactivity=activity; Cocos2dxhelper.addonactivityresultlistener ( This); }
Bluetooth on, need to wait for user feedback Public Static voidOpenbluetooth () {Bluetoothadapter adapter=Bluetoothadapter.getdefaultadapter (); if(!adapter.isenabled ()) {Intent Intent=NewIntent (bluetoothadapter.action_request_enable); Sactivity.startactivityforresult (Intent, Enable_request_code); } }
Callback after user feedback, Openrequesthandler This function is called C + + function @Override Public BooleanOnactivityresult (intRequestcode,intResultCode, Intent data) { Switch(requestcode) { CaseEnable_request_code:if(ResultCode = =SACTIVITY.RESULT_OK) {Openrequesthandler (true); } Else if(ResultCode = =sactivity.result_canceled) {Openrequesthandler (false); } } return true; }}


Again in Frameworks\cocos2d-x\cocos\platform\android\java\src\org\cocos2dx\lib\ Cocos2dxactivity.java Add code to initialize Bluetooth, but it doesn't turn on

protected void onCreate (final  Bundle savedinstancestate) {        ...  This New Cocos2dxbluetooth ();         this. Mbluetooth.init (this);        ....}

Then set the Bluetooth permissions in the Androidmanifest.xml file in the FRAMEWORKS\COCOS2D-X\COCOS\PLATFORM\ANDROID\LIBCOCOS2DX directory, add the following two sentences

<android:name= "Android.permission.BLUETOOTH"/><   android:name= "Android.permission.BLUETOOTH_ADMIN"/>

After the Lua script call c++,c++ and then call the above new Java function Openbluetooth turn on Bluetooth, the following link is Lua call C + + method, very detailed:

Http://segmentfault.com/a/1190000000631630#articleHeader4

and C + + calls Java is done with the Jnihelper class provided by Cocos2d-x, and the following links have detailed methods:

http://blog.csdn.net/yuechuzhao/article/details/9283847

Follow the methods in the link to write your own bluetoothmgr.h,bluetoothmgr.cpp,cocos2dx_bluetooth.ini after use.genbindings.py脚本生成桥接代码

BluetoothMgr.h and BluetoothMgr.cpp are placed in the Frameworks\cocos2d-x\cocos\bluetooth directory, the new directory

BluetoothMgr.h Code:

#ifndef __bluetooth_mgr_h_#define__bluetooth_mgr_h_#include"Platform/ccplatformmacros.h"#include"base/ccref.h"//#include "base/ccconsole.h"#ifCc_target_platform = = Cc_platform_android#include"android/log.h"#include"Platform/android/jni/jnihelper.h"#endifNs_cc_begin#pragmaOnceclassBluetoothmgr: Publicref{ Public: Bluetoothmgr (void); Virtual~bluetoothmgr (void); #ifCc_target_platform = = Cc_platform_android | | Cc_target_platform = = Cc_platform_iosStatic voidOpenbluetooth (); Static voidOpenrequesthandler (BOOLisopened); #endifprotected:}; Ns_cc_end#endif


BluetoothMgr.cpp

#include"BluetoothMgr.h"Ns_cc_beginbluetoothmgr::bluetoothmgr (void) {}bluetoothmgr::~bluetoothmgr (void){}#if(Cc_target_platform = = Cc_platform_android | | Cc_target_platform = = Cc_platform_ios)voidBluetoothmgr::openbluetooth () {Jnimethodinfo minfo; BOOLIshave = Jnihelper::getstaticmethodinfo (Minfo,"Org/cocos2dx/lib/cocos2dxbluetooth","Openbluetooth","() V"); if(ishave) {minfo.env-Callstaticvoidmethod (Minfo.classid, Minfo.methodid); }}voidBluetoothmgr::openrequesthandler (BOOLisopened) {    if(isopened) {__android_log_print (Android_log_debug,"Openrequesthandler","is %s","true"); }Else{__android_log_print (Android_log_debug,"Openrequesthandler","is %s","false"); }}#endif

我是复制cocos2dx_audioengine.ini进行修改成cocos2dx_bluetooth.ini,改了以下地方,都是已经改好了的:

And then execute genbindings.py脚本,位置是frameworks\cocos2d-x\tools\tolua目录下, the first I was directly genbindings.py脚本 dragged into the command window execution, error:

Traceback (most recent):
File "/users/test/frameworks/cocos2d-x/tools/bindings-generator/generator.py", line 1405, in <module>
Main ()
File "/users/test/frameworks/cocos2d-x/tools/bindings-generator/generator.py", line 1380, in main
' Headers ': (Config.get (S, ' headers ', 0, Dict (userconfig.items (' DEFAULT '))),
File "/system/library/frameworks/python.framework/versions/2.7/lib/python2.7/configparser.py", line 623, in Get
return self._interpolate (section, option, value, D)
File "/system/library/frameworks/python.framework/versions/2.7/lib/python2.7/configparser.py", line 691, in _ Interpolate
Self._interpolate_some (option, L, Rawval, section, VARs, 1)
File "/system/library/frameworks/python.framework/versions/2.7/lib/python2.7/configparser.py", line 723, in _ Interpolate_some
option, section, rest, Var)
Interpolationmissingoptionerror:bad Value substitution:
Section: [Cocos2dx_custom]
Option:headers
Key:cocosdir

Then Google found the answer, that is, the CD to the script root directory to run脚本即可解决。

And then the second one is wrong:

Traceback (most recent):
File "D:\soft\workSpace\MyLuaGame\frameworks\cocos2d-x\tools\bindings-generato
r/generator.py ", line 1542, in <module>
Main ()
File "D:\soft\workSpace\MyLuaGame\frameworks\cocos2d-x\tools\bindings-generato
r/generator.py ", line 1476, in main
Raise Exception ("section isn't found in config file")
Exception:section not found in config file
This mistake is forgetting to change the first line of INI file, originally [Cocos2dx_audioengine] to [Cocos2dx_bluetooth].

The generated bridge class code is then embedded in the LUA environment, and the LUA_COCOS2DX_BLUETOOTH_AUTO.HPP function Register_all_cocos2dx_bluetooth is added to the lua_module_register. Remember the Include header file.

Bluetooth is temporarily available on Android and iOS platforms only

When the user clicks on the feedback requires Java to call C + + functions, that is, the most written Openrequesthandler function, you can directly in the cocos2d-x provided frameworks\cocos2d-x\cocos\platform\android Add the following code in the \jni\java_org_cocos2dx_lib_cocos2dxhelper.cpp:

extern " C " {    void jnicall java_org_cocos2dx_lib_cocos2dxbluetooth_openrequesthandler (jnienv * env, Jobject obj, Jboolean isopened) {        bluetoothmgr::openrequesthandler (isopened);    }}

In this way, Java can invoke C + + functions.

Add Bluetooth/bluetoothmgr.cpp to the Local_src_files attribute of the Android.mk file under Frameworks\cocos2d-x\cocos.

In the Local_src_files attribute of the Android.mk file under Frameworks\cocos2d-x\cocos\scripting\lua-bindings\proj.android, add: /auto/lua_cocos2dx_bluetooth_auto.cpp, because lua_cocos2dx_bluetooth_auto.cpp contains the BluetoothMgr.h header file, so local_c_ The includes property also adds $ (local_path)/. /.. /.. /bluetooth, this is the BluetoothMgr.h file path and does not escalate the error that the BluetoothMgr.h file cannot be found.

The new addition method Ccexp is called in the Lua script. Bluetoothmgr:openbluetooth ()

This can be compiled, switch to FRAMEWORKS\RUNTIME-SRC Run command Cocos run-p Android--android-studio build APK package, installed on the phone can be tested.

Very busy recently ... I'll do it slowly.

"Original" cocos2d-x3.9 Bluetooth development Bluetooth enabled

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.