如何使用Ionic-v4检测来电并获取来电号码?

时间:2019-04-10 12:22:54

标签: android angular ionic4 phone-state-listener android-phone-call

我想在使用ionic 4的来电中显示来电号码,这里是我的代码。

home.ts

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

declare var PhoneCallTrap: any;
//phone calls
declare var window: any;

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {

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

  //phone calls
  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]);
  }

  //phone calls
  phonecalls() {
    if (window.PhoneCallTrap) {
      window.PhoneCallTrap.onCall(function (state) {
        alert("CHANGE STATE: " + state);
        //var callObj = JSON.parse(state),
        ///state = callObj.state,
        this.callingNumber = state.incomingNumber;
        alert("callingNumber STATE: " + this.callingNumber);

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

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

我做到了,有了这个,我得到了一个电话状态,就像有人打电话时电话正在振铃,但是我如何获得一个电话号码呢?以及如何从联系人获取来电者的姓名?有什么解决办法吗?

我正在使用此插件:Cordova PhoneCall Trap

0 个答案:

没有答案