How to integrate Bluetooth with IONIC 4 ?

Krunal Shah

Jul 18, 2017 | 5 min read

In recent years IONIC creators have worked hard to match their performances and adaptability to the native coding languages for Android and IOS. IONIC 4 is the framework that is giving the native coding languages a tough time.

To start with we would need to have IONIC installed in your system, if it is already there kudos! And if it’s your first time just follow the few simple steps in below mentioned link.

https://ionicframework.com/docs/intro

Or just run this command in your terminal of the Linux machine.

npm install -g ionic cordova

Now we are all set to take the process further. The application that would be created by following this example will display a list of available device and you can connect or disconnect them. We will start by creating a blank project so follow the steps :).

Step 1:

Run the following command to create your blank project

ionic start bluetoothDemo blank

Now to run the next set of commands you need to navigate to your project directory. You can reach there by using the below command with the folder path of your system.

cd bluetoothDemo

Step 2:

Once you have created the project you have to install the ‘Cordova Bluetooth’ plugin in it which will provide us the Bluetooth back-end driver to perform different functions in the application. Follow the below mentioned command to install the plugin.

ionic cordova plugin add cordova-plugin-bluetooth-serial
npm install @ionic-native/bluetooth-serial

Step 3:

Now you have to import the modules in your ‘app.module.ts’ file located in src/app/app.module.ts file.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';
 
import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';
import { BluetoothSerial } from '@ionic-native/bluetooth-serial/ngx';
 
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
 
@NgModule({
 declarations: [AppComponent],
 entryComponents: [],
 imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule],
 providers: [
   StatusBar,
   SplashScreen,
   BluetoothSerial,
   { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
 ],
 bootstrap: [AppComponent]
})
export class AppModule {}

You are almost there but before you move ahead do not forget to add the ‘BluetoothSerial’ to the providers list as seen in the above example. Now the Bluetooth plugin is completely bind with your application and it could now be used wherever you want by simply importing it in your “page’s .ts” file.

Now here in our blank project first paste the above line of code in app.module.ts and import it in your page.

Step 4:

Add following lines of code in your home.html file which is located in src/app/home/home.html

<ion-content>
    <ion-list padding>
        <ion-button expand="block"
                    (click)="startScanning()">scan</ion-button>
        <ion-list-header>
            Paired Devices
        </ion-list-header>
        <ion-item *ngFor="let device of pairedDevices">
            {{device.name}}
        </ion-item>
        <ion-button expand="block"
                    (click)="disconnect()">Disconnect</ion-button>
        <ion-list-header>
            availlable Devices
        </ion-list-header>
        <ion-item *ngFor='let device of unpairedDevices'>
            <span (click)="selectDevice(device.id)">
                {{device.name || device.address}}
            </span>
        </ion-item>
        <ion-spinner name="crescent"
                     *ngIf="gettingDevices"></ion-spinner>
    </ion-list>
</ion-content>

Above line of code will provide you the view part of your application. You can customize your view according your need. So now we have the structure ready i.e. the drawing of the app is created but we of-course we need to have logic that comes in to play while you click a button. Hence this logic can be written to the home.ts file of your project which is also located in the home folder of the project. Add the following code to ‘home.ts’ to add the business logic. The file will be located at the following path src/app/home/home.ts file.

import { Component } from '@angular/core';
import { BluetoothSerial } from '@ionic-native/bluetooth-serial/ngx';
import { AlertController } from '@ionic/angular';
 
@Component({
 selector: 'app-home',
 templateUrl: 'home.page.html',
 styleUrls: ['home.page.scss'],
})
export class HomePage {
 
 unpairedDevices: any;
 pairedDevices: any;
 gettingDevices: boolean;
 
 constructor(private bluetoothSerial: BluetoothSerial, private alertController: AlertController) {
   bluetoothSerial.enable();
 }
 
 startScanning() {
   this.pairedDevices = null;
   this.unpairedDevices = null;
   this.gettingDevices = true;
   const unPair = [];
   this.bluetoothSerial.discoverUnpaired().then((success) => {
     success.forEach((value, key) => {
       var exists = false;
       unPair.forEach((val2, i) => {
         if (value.id === val2.id) {
           exists = true;
         }
       });
       if (exists === false && value.id !== '') {
         unPair.push(value);
       }
     });
     this.unpairedDevices = unPair;
     this.gettingDevices = false;
   },
     (err) => {
       console.log(err);
     });
 
   this.bluetoothSerial.list().then((success) => {
     this.pairedDevices = success;
   },
     (err) => {
 
     });
   }
 
 success = (data) => {
   this.deviceConnected();
 }
 fail = (error) => {
   alert(error);
 }
 
 async selectDevice(id: any) {
 
   const alert = await this.alertController.create({
     header: 'Connect',
     message: 'Do you want to connect with?',
     buttons: [
       {
         text: 'Cancel',
         role: 'cancel',
         handler: () => {
           console.log('Cancel clicked');
         }
       },
       {
         text: 'Connect',
         handler: () => {
           this.bluetoothSerial.connect(id).subscribe(this.success, this.fail);
         }
       }
     ]
   });
   await alert.present();
 }
 
 deviceConnected() {
   this.bluetoothSerial.isConnected().then(success => {
     alert('Connected Successfullly');
   }, error => {
     alert('error' + JSON.stringify(error));
   });
 }
 
 async disconnect() {
   const alert = await this.alertController.create({
     header: 'Disconnect?',
     message: 'Do you want to Disconnect?',
     buttons: [
       {
         text: 'Cancel',
         role: 'cancel',
         handler: () => {
           console.log('Cancel clicked');
         }
       },
       {
         text: 'Disconnect',
         handler: () => {
           this.bluetoothSerial.disconnect();
         }
       }
     ]
   });
   await alert.present();
 }
}

The demo application is ready to run. To test the application you just need to create an APK for your android device. Install it in the device that has a properly functioning Bluetooth and you can view available devices, pair it and view the paired devices.

Now this is just a demo app and you are testing it so you would like to avoid the pain to create an APK and then install it just to test instead just follow the steps mentioned in our blog “How to run IONIC application in android using ubuntu?”to test your application.

You can do a variety of operations with the IONIC Bluetooth serial plugin which can provide better features to your application for this you can refer to the link mentioned below.

https://github.com/don/BluetoothSerial

Limitations

  • The phone must initiate the Bluetooth connection
  • iOS Bluetooth Low Energy requires iPhone 4S, iPhone5, iPod 5, or iPad3+
  • Will not connect Android to Android*
  • Will not connect iOS to iOS*

The application will look in the device something like the following image. There are two buttons available one is to scan available devices and paired devices. When we click on any available devices it will ask to connect to that device and after you have clicked on the connect button the device will be connected to that device. You would also see one more button called ‘Disconnect’ to disconnect the connected device.

Let us know your experience with IONIC and Bluetooth. Your feedback is what keeps us going !!

Please share your feedback. :)

· · · ·

Third Rock Techkno is a leading IT services company. We are a top-ranked web, voice and mobile app development company with over 10 years of experience. Client success forms the core of our value system.

We have expertise in the latest technologies including angular, react native, iOs, Android and more. Third Rock Techkno has developed smart, scalable and innovative solutions for clients across a host of industries.

Our team of dedicated developers combine their knowledge and skills to develop and deliver web and mobile apps that boost business and increase output for our clients.