Bluetooth is a software(Based on wireless technology) which is generally used for making the communication or information exchange…

…between two electronic devices such as mobile phone computer tablet etc.

Though we have various fast data transfer technology today, which are capable to exchange data with a very fast speed rate, still we are carying and upgrading this bluetoth technology with time…

…because of its amazing merits such as low cost, low interference, automatic, low energy consumption, Instant PAN(Personal Area Network).

In This post we are going to explain how to turn on your device bluetooth with a phonegap application. You will also be able to see a bluetooth device list connected or paired with your device.



Start building your first PhoneGap Device Info application:

I am explaining this code project by keeping a  focus on the android platform, but it will be a similar procedure to make it run across all platforms.

To develop a mobile application, you need to make some setup which is listed below:

  1.  Install Node.js.
  2.  Install Android Studio
  3. Install Apache ANT
  4. Install GIT Command Line

Note:-  We are using Android Studio for launching the emulator and see the result of our application code. we are not doing any programming in android studio except the configuration like installation of all possible supporting features.

You have to choose only your android version which support your device and you will get all the required features to be downloaded with the automatic path set too.

Install PhoneGap/Cordova:

You can install it two ways either PhoneGap CLI(Command Line Interface) mode or PhoneGap desktop(GUI) mode.

I am using a desktop PhoneGap installation here but if you want to try it with PhoneGap CLI then follow command listed below.

C:\>npm install -g Cordova
C:\>npm install -g PhoneGap
Create New PhoneGap Project & Add required Platforms such as android:
$ Cordova create PhoneGapBluetooth
Add Platforms:
$ Cordova platform add android
Add Device Plugin:
$ cordova plugin add cordova-plugin-bluetooth-status
$ cordova plugin add cordova-plugin-bluetooth-serial
Run Project:
$ cordova build phonegapbluetooth
$ cordova emulate phonegapbluetooth

Note: If you are facing any problem regarding PhoneGap Installation or Plugin Installation then you can go through following blog post:

Learn how to install PhoneGap?

Learn how to create, run, build PhoneGap build?

Learn how to use PhoneGap Plugin API?

Complete Code:

You can try by just copy & paste the below code files.

index.html:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, target-densitydpi=device-dpi" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
<link href='https://fonts.googleapis.com/css?family=Fjalla+One' rel='stylesheet' type='text/css'>
<title>PhoneGap Bluetooth</title>
</head>
<body>
<div class="app">
<h1>PhoneGap Bluetooth</h1>
<div id="mainPage">
<ul id="deviceList">
</ul>
<button id="refreshButton" class ="styled-button-9">Get Your Bluetooth Devices</button>
</div>
<div id="detailPage">
<div id="resultDiv"></div>
</div>
<div id="statusDiv"></div>
</div>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript">
app.initialize();
</script>
</body>
</html>

index.css:

body {
font-family: 'Fjalla One', sans-serif;
font-weight: bold;
color: #2a2a2a;
background-color: #3eb0f7;
-webkit-appearance: none;
-webkit-touch-callout: none;
-webkit-tap-highlight-color: rgba(0,0,0,0);
-webkit-touch-callout: none; -webkit-user-select: none;
}

h1 {
text-align: center;
font-family: 'Fjalla One', sans-serif;
color:white;
}

#mainPage {
text-align:center;
}

#detailPage {
text-align:center;
font-size: 2em;
}

#detailPage div {
margin: 20px;
}

#detailPage button {
margin-top: 40px;
font-size: 0.6em; /* undo 2em from parent */
}

ul {
list-style: none;
border-bottom: 1px solid #d3d3d3;
text-align: center;
font-family: 'Fjalla One', sans-serif;
color:white;
}

li {
margin-left: -40px;
padding: 5px;
padding-top: 10px;
min-height: 50px;
border-top: 1px solid #d3d3d3;
font-size: 16px;
}

#resultDiv {
font: 16px "Source Sans", helvetica, arial, sans-serif;
font-weight: 200;
display: block;
-webkit-border-radius: 6px;
width: 100%;
height: 140px;
text-align: left;
overflow: auto;
}

#statusDiv {
text-align: center;
margin-top: 9px;
color:white;
}

.fadein {
opacity: 1;
-webkit-transition: opacity 1s ease-in;
}

.fadeout {
opacity: 0;
-webkit-transition: opacity 1s ease-out;
}
@media screen and (device-aspect-ratio: 40/71) {
h1 {
font-size: 1.6em;
padding-top: 15px;
}

input[type=text] {
font-size: 0.5em;
}
}
.styled-button-9 {
background: #00A0D1;
background: -moz-linear-gradient(top,#00A0D1 0%,#008DB8 100%);
background: -webkit-gradient(linear,left top,left bottom,color-stop(0%,#00A0D1),color-stop(100%,#008DB8));
background: -webkit-linear-gradient(top,#00A0D1 0%,#008DB8 100%);
background: -o-linear-gradient(top,#00A0D1 0%,#008DB8 100%);
background: -ms-linear-gradient(top,#00A0D1 0%,#008DB8 100%);
background: linear-gradient(top,#00A0D1 0%,#008DB8 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#00A0D1',endColorstr='#008DB8',GradientType=0);
padding:8px 20px;
color:#cfebf3;
font-family: 'Fjalla One', sans-serif;
font-size:16px;
margin-top:22%;
border-radius:40px;
-moz-border-radius:40px;
-webkit-border-radius:40px;
border:1px solid #095B7E

}

index.js:

var app = {
initialize: function() {
this.bindEvents();
this.showMainPage();
},
bindEvents: function() {
var TOUCH_START = 'touchstart';
if (window.navigator.msPointerEnabled) { // windows phone
TOUCH_START = 'MSPointerDown';
}
document.addEventListener('deviceready', this.onDeviceReady, false);
refreshButton.addEventListener(TOUCH_START, this.refreshDeviceList, false);
sendButton.addEventListener(TOUCH_START, this.sendData, false);
disconnectButton.addEventListener(TOUCH_START, this.disconnect, false);
deviceList.addEventListener(TOUCH_START, this.connect, false);
},
onDeviceReady: function() {
//This function will be used for switching on the device bluetooth
cordova.plugins.BluetoothStatus.promptForBT();
window.bluetooth = cordova.require("cordova/plugin/bluetooth");
function yourCallbackFunction(){
window.bluetooth = cordova.require("cordova/plugin/bluetooth");
}
bluetoothSerial.isEnabled(success, failure);
alert('device is ready');
app.refreshDeviceList();
},
refreshDeviceList: function() {
alert('Get the Device List');
bluetoothSerial.list(app.onDeviceList, app.onError);
},
onDeviceList: function(devices) {
var option;
// remove existing devices
deviceList.innerHTML = "";
app.setStatus("");
devices.forEach(function(device) {
var listItem = document.createElement('li'),
html = '<b>' + device.name + '</b><br/>' + device.id;
listItem.innerHTML = html;
if (cordova.platformId === 'windowsphone') {
// This is a temporary hack until I get the list tap working
var button = document.createElement('button');
button.innerHTML = "Connect";
button.addEventListener('click', app.connect, false);
button.dataset = {};
button.dataset.deviceId = device.id;
listItem.appendChild(button);
} else {
listItem.dataset.deviceId = device.id;
}
deviceList.appendChild(listItem);
});
if (devices.length === 0) {
option = document.createElement('option');
option.innerHTML = "No Bluetooth Devices";
deviceList.appendChild(option);
if (cordova.platformId === "ios") { // BLE
app.setStatus("No Bluetooth Peripherals Discovered.");
} else { // Android or Windows Phone
app.setStatus("Please Pair a Bluetooth Device.");
cordova.plugins.BluetoothStatus.promptForBT();
}
} else {
app.setStatus("Found " + devices.length + " device" + (devices.length === 1 ? "." : "s."));
}
},
showMainPage: function() {
mainPage.style.display = "";
detailPage.style.display = "none";
},
showDetailPage: function() {
mainPage.style.display = "none";
detailPage.style.display = "";
},
setStatus: function(message) {
console.log(message);
window.clearTimeout(app.statusTimeout);
statusDiv.innerHTML = message;
statusDiv.className = 'fadein';
// automatically clear the status with a timer
app.statusTimeout = setTimeout(function () {
statusDiv.className = 'fadeout';
}, 5000);
},
onError: function(reason) {
alert("ERROR: " + reason); // real apps should use notification.alert
}
};

Conclusion:

Now, after reading this post you are able to turn on the device bluetooth using PhoneGap API. You can also get a device list which are ready to connect and pair with your bluetooth device. We will keep you updating on the same, so keep reading our blog post.

You may also have a look on some informative blogs below –