Ionic 3 暂停和恢复事件在 Android 中触发多次

Ionic 3 pause and resume events triggering multiple times in Android

我在 ionic 3 暂停和恢复事件中遇到了一个奇怪的问题,每当我暂停应用程序时,事件都会调用多次(一次 2,一次 3 等)。 这是代码

 this.platform.ready().then(() => {
  this.platform.pause.subscribe(() => {        
      console.log('****UserdashboardPage PAUSED****');
  });  
  this.platform.resume.subscribe(() => {      
      console.log('****UserdashboardPage RESUMED****');
  });
});

我已经尝试将相同的代码放在 ionViewDidLoad、Constructor、ionViewWillEnter 中,但仍然面临同样的问题。请任何人帮助我解决这个问题。应用程序恢复后,我正在调用一项服务,但现在它正在调用多个 times.Thanks!!

它会调用多次,因为每次您暂停或恢复应用程序时,它都会订阅平台。 您需要按照以下方式退订平台

private sub1$:any;
private sub2$:any;

this.platform.ready().then(() => {
  this.sub1$=this.platform.pause.subscribe(() => {        
      console.log('****UserdashboardPage PAUSED****');
  });  
  this.sub2$=this.platform.resume.subscribe(() => {      
      console.log('****UserdashboardPage RESUMED****');
  });
});

ionViewWillUnload() {
    this.sub1$.unsubscribe();
    this.sub2$.unsubscribe();
  }

希望有用。

import { Platform } from '@ionic/angular';
import { Component } from '@angular/core';
import { Subscription } from 'rxjs';


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


  constructor(private platform:Platform) {}
  resumeListener:Subscription=new Subscription();
ionViewWillEnter() {
  this.resumeListener=this.platform.resume.subscribe(()=>{
    console.log("resume")

  })
}

  ionViewWillLeave() {
    this.resumeListener.unsubscribe();
  
  }

}

即使你有多个选项卡也能正常工作 你可以用暂停事件做同样的事情