Polymer - Platinum Bluetooth
它用于使用 <platinum-bluetooth> 元素与附近的蓝牙设备进行交互。
您可以在应用程序中使用此元素,方法是运行以下命令将其安装在项目目录中。
bower install --save PolymerElements/platinum-bluetooth
示例
以下示例指定了在 Polymer.js 中使用 platinum-bluetooth 元素。创建一个 index.html 文件并在其中添加以下代码。
<!doctype html> <html> <head> <title>Polymer Example</title> <script src = "bower_components/webcomponentsjs/webcomponents-lite.js"></script> <link rel = "import" href = "bower_components/polymer/polymer.html"> <link rel = "import" href = "bower_components/paper-styles/demo-pages.html"> <link rel = "import" href = "bower_components/paper-button/paper-button.html"> <link rel = "import" href = "bower_components/platinum-bluetooth/platinum-bluetooth-device.html"> </head> <body> <section> <paper-button raised>Get bluetooth device</paper-button> </section> <script src = "platinum_bluetooth.js"></script> </body> </html>
现在,创建另一个名为 platinum_bluetooth.js 的文件并包含以下代码 −
document.addEventListener('WebComponentsReady', function() { var mybatteryDevice = document.querySelector('platinum-bluetooth-device'); var mybutton = document.querySelector('paper-button'); mybutton.addEventListener('click', function() { console.log('The requested bluetooth device advertising a battery service...'); mybatteryDevice.request().then(function(device) { console.log('Bluetooth device has been found...'); console.log('The device name is: ' + device.name); }) .catch(function(error) { console.error('Sorry!No device found...', error); }); }); });
输出
要运行应用程序,请导航到创建的项目目录并运行以下命令。
polymer serve
现在打开浏览器并导航到 http://127.0.0.1:8081/。以下是输出。

单击按钮时,它将在控制台中显示一条消息"The requested bluetooth device advertising a battery service...",如果未找到设备,则显示一条错误消息。