Native. js Acquire Android Bluetooth Device Example Code for Snoop Switch and Other Operating Android

  • 2021-10-15 11:38:57
  • OfStack

Native. js Turn Bluetooth on and off


var main = plus.android.runtimeMainActivity();
var Context = plus.android.importClass("android.content.Context");
var BManager = main.getSystemService(Context.BLUETOOTH_SERVICE);
plus.android.importClass(BManager);// Introduce related method Function 
var BAdapter = BManager.getAdapter();
plus.android.importClass(BAdapter);// Introduce related method Function, so that there will be a isEnabled Function support 
if(!BAdapter.isEnabled()) {
BAdapter.enable();
}

Native. js Monitor Bluetooth Switch Status


var main = plus.android.runtimeMainActivity();
var BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");
var BAdapter = new BluetoothAdapter.getDefaultAdapter();
var resultDiv = document.getElementById('output');
var receiver=plus.android.implements('io.dcloud.android.content.BroadcastReceiver', {
onReceive: function(context, intent) { // Realization onReceiver Callback function 
 plus.android.importClass(intent);
 console.log(intent.getAction());
 resultDiv.textContent += '\nAction :' + intent.getAction();
 main.unregisterReceiver(receiver);
 }
});
var IntentFilter = plus.android.importClass('android.content.IntentFilter');
var filter = new IntentFilter();
filter.addAction(BAdapter.ACTION_STATE_CHANGED); // Monitor Bluetooth switch 
main.registerReceiver(receiver, filter); // Register monitor 

if (!BAdapter.isEnabled()) {
 BAdapter.enable(); // Start Bluetooth 
}else{
 BAdapter.disable();
}

Native. js Get a list of Bluetooth devices


unction bluetooth_list(){
var main = plus.android.runtimeMainActivity();
var Context = plus.android.importClass("android.content.Context");
var lists = BAdapter.getBondedDevices();
plus.android.importClass(lists);
var resultDiv = document.getElementById('bluetooth_list');
var iterator = lists.iterator();
plus.android.importClass(iterator);
while (iterator.hasNext()) {
var d = iterator.next();
plus.android.importClass(d);
console.log(d.getAddress());
}
}

Native. js Bluetooth Connected Bill Printer

Tester: Jiabo PT-280 portable printer
Mobile phone: Huawei low-end
Function: Scan the list of Bluetooth devices around, click on unpaired devices, automatically paired devices, and paired devices for printing test

html page code


<!DOCTYPE html>
<html>
 <head>
 <meta charset="UTF-8">
 <title></title>
 <script src="js/pr.js"></script>
 </head>
 <body>
 <div>
 <p><input id="bt1" type="button" value=" Search equipment " onclick="searchDevices('a')"></p>
 </div>
 <div>
  Unpaired Bluetooth device 
 <ul id="list1">

 </ul>
 </div>

 <div>
  Paired Bluetooth device 

 <ul id="list2">

 </ul>
 </div>
 </body>
</html>

Js file


//address="" Search Bluetooth //address= Equipment mac Address, automatic pairing given mac Address of the device 
function searchDevices(address) {
 // Register class 
 var main = plus.android.runtimeMainActivity();
 var IntentFilter = plus.android.importClass("android.content.IntentFilter");
 var BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");
 var BluetoothDevice = plus.android.importClass("android.bluetooth.BluetoothDevice");
 var BAdapter = BluetoothAdapter.getDefaultAdapter();
 console.log(" Start searching for equipment ");
 var filter = new IntentFilter();
 var bdevice = new BluetoothDevice();
 var on = null;
 var un = null;
 var vlist1 = document.getElementById("list1"); // The registration container is used to display unpaired devices 
 vlist1.innerHTML = ""; // Empty a container 
 var vlist2 = document.getElementById("list2"); // The registration container is used to display unpaired devices 
 vlist2.innerHTML = ""; // Empty a container 
 var button1 = document.getElementById("bt1");
 button1.disabled=true;
 button1.value=" Please wait while searching ";
 BAdapter.startDiscovery(); // Start search 
 var receiver;
 receiver = plus.android.implements("io.dcloud.android.content.BroadcastReceiver", {
 onReceive: function(context, intent) { // Realization onReceiver Callback function 
 plus.android.importClass(intent); // Pass intent Instance introduction intent Class, convenient for future ' .' Operation 
 console.log(intent.getAction()); // Get action
 if(intent.getAction() == "android.bluetooth.adapter.action.DISCOVERY_FINISHED"){
 main.unregisterReceiver(receiver);// Cancel listening 
 button1.disabled=false;
 button1.value=" Search equipment ";
 console.log(" End of search ");
 }else{
 BleDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
 // Determine whether to pair or not 
 if (BleDevice.getBondState() == bdevice.BOND_NONE) {
 console.log(" Unpaired Bluetooth devices: " + BleDevice.getName() + " " + BleDevice.getAddress());
 // Parameter if it follows the obtained mac Address 1 Pair the sample 
 if (address == BleDevice.getAddress()) {
  if (BleDevice.createBond()) { // Pairing command .createBond()
  console.log(" Successful pairing ");
  var li2 = document.createElement("li"); // Registration 
  li2.setAttribute("id", BleDevice.getAddress()); // Printer mac Address 
  li2.setAttribute("onclick", "print(id)"); // Registration click Click on the list to print 
  li2.innerText = BleDevice.getName();
  vlist2.appendChild(li2);
  }

 } else {
  if(BleDevice.getName() != on ){ // Judge to prevent repeated addition 
  var li1 = document.createElement("li"); // Registration 
  li1.setAttribute("id", BleDevice.getAddress()); // Printer mac Address 
  li1.setAttribute("onclick", "searchDevices(id)"); // Registration click Click on the list to pair 
  on = BleDevice.getName();
  li1.innerText = on;
  vlist1.appendChild(li1);

  }

 }
 } else {
 if(BleDevice.getName() != un ){ // Judge to prevent repeated addition 
 console.log(" Paired Bluetooth device: " + BleDevice.getName() + " " + BleDevice.getAddress());
 var li2 = document.createElement("li"); // Registration 
 li2.setAttribute("id", BleDevice.getAddress()); // Printer mac Address 
 li2.setAttribute("onclick", "print(id)"); // Registration click Click on the list to print 
 un = BleDevice.getName(); 
 li2.innerText = un;
 vlist2.appendChild(li2);}
 }}
 }
 });

 filter.addAction(bdevice.ACTION_FOUND);
 filter.addAction(BAdapter.ACTION_DISCOVERY_STARTED);
 filter.addAction(BAdapter.ACTION_DISCOVERY_FINISHED);
 filter.addAction(BAdapter.ACTION_STATE_CHANGED);

 main.registerReceiver(receiver, filter); // Register monitor 
}

var device = null,
 BAdapter = null,
 BluetoothAdapter = null,
 uuid = null,
 main = null,
 bluetoothSocket = null;

function print(mac_address) {
 if (!mac_address) {
 mui.toast(" Please select a Bluetooth printer ");
 return;
 }

 main = plus.android.runtimeMainActivity();
 BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");
 UUID = plus.android.importClass("java.util.UUID");
 uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
 BAdapter = BluetoothAdapter.getDefaultAdapter();
 device = BAdapter.getRemoteDevice(mac_address);
 plus.android.importClass(device);
 bluetoothSocket = device.createInsecureRfcommSocketToServiceRecord(uuid);
 plus.android.importClass(bluetoothSocket);

 if (!bluetoothSocket.isConnected()) {
 console.log(" Device not connected detected, attempting to connect ....");
 bluetoothSocket.connect();
 }

 console.log(" Device Connected ");

 if (bluetoothSocket.isConnected()) {
 var outputStream = bluetoothSocket.getOutputStream();
 plus.android.importClass(outputStream);
 var string = " Print test \r\n";
 var bytes = plus.android.invoke(string, "getBytes", "gbk");
 outputStream.write(bytes);
 outputStream.flush();
 device = null // The key here 
 bluetoothSocket.close(); // You must close the Bluetooth connection or print errors if you accidentally disconnect it 

 }

}

The above is the operation example code of Native. js to Android Bluetooth device. If you want to know other example codes of Native. js or native Android Bluetooth operation method, please see the relevant links below


Related articles: