Search code examples
ionic-frameworkcapacitorcapacitor-plugin

Ionic 5, how to get the serial number of device via capacitor?


I'm building an app by using Ionic 5 & CapacitorJs, I want to know how to get the serial number via the capacitor plugin?

I don't want to use the Cordova plugin if possible.


Solution

  • You can read IMEI, ICCID, IMSI and MAC with Ionic Device

    First of all you need to install plugins

    $ ionic cordova plugin add cordova-plugin-uid
    $ npm install @ionic-native/uid
    
    $ ionic cordova plugin add cordova-plugin-android-permissions
    $ npm install @ionic-native/android-permissions 
    

    Or with capacitor:

    npm install @ionic-native/android-permissions
    npm install cordova-plugin-android-permissions
    npm install cordova-plugin-uid
    npm install @ionic-native/uid
    
    ionic cap sync
    

    So you need to implement something like this:

    import { Component } from '@angular/core';
        
        import { UniqueDeviceID } from '@ionic-native/unique-device-id/ngx';
        import { Uid } from '@ionic-native/uid/ngx';
        import { AndroidPermissions } from '@ionic-native/android-permissions/ngx';
        
        @Component({
          selector: 'app-home',
          templateUrl: 'home.page.html',
          styleUrls: ['home.page.scss'],
        })
        export class HomePage {
        
          constructor(
            private uniqueDeviceID: UniqueDeviceID,
            private uid: Uid,
            private androidPermissions: AndroidPermissions
          ) {
          }
        
            ...
            ...
        
        }
    

    And

      getPermission(){
        this.androidPermissions.checkPermission(
          this.androidPermissions.PERMISSION.READ_PHONE_STATE
        ).then(res => {
          if(res.hasPermission){
            
          }else{
            this.androidPermissions.requestPermission(this.androidPermissions.PERMISSION.READ_PHONE_STATE).then(res => {
              alert("Persmission Granted Please Restart App!");
            }).catch(error => {
              alert("Error! "+error);
            });
          }
        }).catch(error => {
          alert("Error! "+error);
        });
      }
    

    And

      getID_UID(type){
        if(type == "IMEI"){
          return this.uid.IMEI;
        }else if(type == "ICCID"){
          return this.uid.ICCID;
        }else if(type == "IMSI"){
          return this.uid.IMSI;
        }else if(type == "MAC"){
          return this.uid.MAC;
        }else if(type == "UUID"){
          return this.uid.UUID;
        }
      }
    

    OR MAYBE BETTER

    getID_UID = (type) => (this.uid[type])