2019年12月23日 星期一

[morse]Ionic 檢查設備硬件功能是否已啟用或對應用程序可用


Install
    ionic cordova plugin add cordova.plugins.diagnostic
    npm install @ionic-native/diagnostic



Example 1:

import { Diagnostic } from '@ionic-native/diagnostic/ngx';
constructor(private diagnostic: Diagnostic) { }
...
let successCallback = (isAvailable) => { console.log('Is available? ' + isAvailable); }
let errorCallback = (e) => console.error(e);
this.diagnostic.isCameraAvailable().then(successCallback).catch(errorCallback);
this.diagnostic.isBluetoothAvailable().then(successCallback, errorCallback);

this.diagnostic.getBluetoothState()
.then((state) => {
    if (state == this.diagnostic.bluetoothState.POWERED_ON){
    // do something
    } else {
    // do something else
    }
}).catch(e => console.error(e));


Example 2:

app.module.ts

import { Diagnostic } from '@ionic-native/diagnostic/ngx';

@NgModule({
  providers: [
    Diagnostic
  ]
})


xxx.page.ts

  import { Diagnostic } from '@ionic-native/diagnostic/ngx';

  constructor(private _diagnostic: Diagnostic) { }
  
  Gpsstart() {
    // 檢查GPS
    this._diagnostic.isGpsLocationEnabled().then(
      (OnSuccess) => {
        if (OnSuccess){
          alert('GPS 開啟中');          
          this.showWatch();  
        }
        else{
          alert('GPS 沒開啟!');
          // 進入 GPS 啟用設定畫面
          this._diagnostic.switchToLocationSettings();  
        }
      },
      (OnFail) => {
        alert('GPS 檢查時出現錯誤!');
        this._totast.presentToastWithOptions('GPS 檢查時出現錯誤! '+ OnFail.message);
        //cordova.plugins.diagnostic.switchToLocationSettings();
      }
    ).catch(
      (OnError) => {
        this._totast.presentToastWithOptions('Catch error: ' + OnError.message);
      }
    );    
  }
  
  gpsWatch() {
    this.watchPosition = undefined;
    const options = {
      enableHighAccuracy: true,
      timeout: 5000,
      maximumAge: 0
    };
    this.gpsWatchId = this._geolocation.watchPosition(options).subscribe(
      (p) => {
        if (p) {
          this.watchPosition = p;
        }
        //alert(p.coords.latitude);
      },
      error => {
        // console.log('GPS Watch fail!');
        // console.error(error);
        // this._totast.presentToastWithOptions(error.message);
        alert(error.message);
      }
    );
  }



referance :
如何檢查是否啟用了gps
https://stackoverflow.com/questions/35304103/phonegap-how-to-check-if-gps-is-enabled

診斷-檢查設備硬件功能是否已啟用或對應用程序可用,例如相機,GPS,WiFi
https://ionicframework.com/docs/native/diagnostic

沒有留言:

張貼留言