离子3 - 如何检索来电号码?

时间:2018-04-30 11:32:11

标签: cordova ionic3

我正在尝试接收离子3中的来电号码。我正在使用https://www.npmjs.com/package/cozzbie.plugin.phonecalltrap执行此操作。 它可以很好地检测手机状态,但不会返回来电号码。

我正在使用下面的代码,

declare var PhoneCallTrap:any;

if (PhoneCallTrap) 
    {
      PhoneCallTrap.onCall(function(obj) {
        var callObj = JSON.parse(obj),
            state = callObj.state,
            callingNumber = callObj.incomingNumber;

        switch (state) {
            case "RINGING":
                console.log("Phone is ringing =" + callingNumber);
                break;
            case "OFFHOOK":
                console.log("Phone is off-hook");
                break;

            case "IDLE":
                console.log("Phone is idle");
                break;
        }
      });
    } 

是否有任何其他想法或插件可以检索电话号码

1 个答案:

答案 0 :(得分:0)

您正在使用正确的插件,您的代码也不错,但您只需要添加正确的android权限即可从移动设备访问数据。为此,请遵循以下代码。

将此插件添加到您的项目中:

打开app.module.ts文件,如下所示:

import { AndroidPermissions } from '@ionic-native/android-permissions/ngx';

providers: [ AndroidPermissions ],

打开homePage.ts文件导入AndroidPermissions并添加以下代码:

import { AndroidPermissions } from '@ionic-native/android-permissions/ngx';

declare var PhoneCallTrap: any;

constructor(public androidPermissions: AndroidPermissions){
  this.checkPermissionCall();
  this.checkPermissionREAD_CONTACTS();
}

//READ_PHONE_STATE
checkPermissionCall() {
  this.androidPermissions.checkPermission(this.androidPermissions.PERMISSION.READ_PHONE_STATE).then(
    success => {
      //if permission granted
      this.phonecalls();
    },
    err => {
      this.androidPermissions.requestPermission(this.androidPermissions.PERMISSION.READ_PHONE_STATE).
        then(success => {
          this.phonecalls();
        },
          err => {
            console.log("cancelled")
          });
    });
  this.androidPermissions.requestPermissions([this.androidPermissions.PERMISSION.READ_PHONE_STATE]);
}

//READ_PHONE_STATE
checkPermissionREAD_CONTACTS() {
  this.androidPermissions.checkPermission(this.androidPermissions.PERMISSION.READ_CONTACTS).then(
    success => {
      //if permission granted
    },
    err => {
      this.androidPermissions.requestPermission(this.androidPermissions.PERMISSION.READ_CONTACTS).
        then(success => {
        },
          err => {
            console.log("cancelled")
          });
    });
  this.androidPermissions.requestPermissions([this.androidPermissions.PERMISSION.READ_CONTACTS]);
}

//phone calls
phonecalls() {
  PhoneCallTrap.onCall(function (obj) {

    var callObj = JSON.parse(obj),
      state = callObj.state,
      callingNumber = callObj.incomingNumber;

    switch (state) {
      case "RINGING":
        console.log("Phone is ringing", callingNumber);
        break;
      case "OFFHOOK":
        console.log("Phone is off-hook");
        break;

      case "IDLE":
        console.log("Phone is idle");
        break;
    }
  });
}

我尝试像您一样,但是我无法获得号码,但是经过艰苦的工作和搜索,我得到了这个,有了这个,您将得到号码和状态。

希望它对您有帮助:)