我有问题,让我的应用程序在后台运行,其中之一是应用程序跟踪位置时,设备是在后台模式。一切正常,但后台服务只工作2分钟。我正在pie - Android 9上进行测试。我从android文档中看到,我需要为android 8及更高版本使用前台服务。我想知道前台服务在我的离子4.6应用程序中的实现
我的app.component.ts文件代码。
import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { Platform } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';
import { AngularFireAuth } from '@angular/fire/auth';
import { ForegroundService } from '@ionic-native/foreground-service/ngx';
declare var cordova: any;
@Component({
selector: 'app-root',
templateUrl: 'app.component.html'
})
export class AppComponent {
constructor(
private router: Router,
private platform: Platform,
private splashScreen: SplashScreen,
private statusBar: StatusBar,
private fireAuth: AngularFireAuth,
public foregroundService: ForegroundService
) {
this.initializeApp();
}
initializeApp() {
this.platform.ready().then(() => {
cordova.plugins.backgroundMode.on('activate', () => {
cordova.plugins.backgroundMode.disableWebViewOptimizations();
cordova.plugins.backgroundMode.disableBatteryOptimizations();
console.log('ACTIVATE background mode1');
cordova.plugins.backgroundMode.setEnabled(true);
});
this.fireAuth.auth.onAuthStateChanged(user => {
if (user) {
this.router.navigate(['/tabs/tab2']);
} else {
this.router.navigate(['/slider']);
this.splashScreen.hide();
}
});
this.statusBar.styleDefault();
this.foregroundService.start('GPS Running', 'Background Service', 'drawable/fsicon');
});
}
}发布于 2020-12-03 20:12:19
将BackgroundMode和ForegroundService添加到app.module.ts中的提供程序列表中
import { ForegroundService } from '@ionic-native/foreground-service/ngx';
import { BackgroundMode } from '@ionic-native/background-mode/ngx';
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';
import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
@NgModule({
declarations: [AppComponent],
entryComponents: [],
imports: [
BrowserModule,
IonicModule.forRoot(),
AppRoutingModule,
],
providers: [
StatusBar,
SplashScreen,
{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy },
BackgroundMode,
ForegroundService,
],
bootstrap: [AppComponent]
})
export class AppModule {}此外,还需要将以下代码添加到config.xml文件中
<platform name="android">
.
.
.
<config-file parent="/*" target="AndroidManifest.xml">
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
</config-file>
</platform>https://stackoverflow.com/questions/59834016
复制相似问题