![](/img/trans.png)
[英]Android:How to make notification to be compatible with both API 26+ and below?
[英]How can I implement Android Background Service in NativeScript targeting both API Level 26+ and below
我需要在 NativeScript 中實現后台服務,它將每 x 分鍾獲取用戶位置,向我的 API 發出請求,並根據響應發出本地通知。
所以我開始尋找實現這一點的方法,這讓我找到了這個 NativeScript存儲庫。 如自述文件中所述:
當前實現使用 NotificationChannel,它是在 API 級別 26 中添加的。如果您想針對較低的 API 級別,請查看較舊的實現警報管理器實現。 請記住,由於操作系統的限制,API 級別 26 或更高版本不支持此方法。
我需要支持 Android 5.1+(API 級別 22+),所以新的實現對我不起作用,相反,我應該使用前面提到的舊的警報管理器實現。 問題是,正如您在引用中看到的那樣,API Level 26+ 不支持這種方法。
眾所周知,Google 正在強制新應用程序至少以 API 級別 28 為目標。那么,我怎樣才能實現從 API 級別 22 到 28 的后台服務?
您可以參考nativescript-geolocation插件 repo 中的示例,適用於所有受支持的 Android 版本。
if (device.sdkVersion < "26") {
@JavaProxy("com.nativescript.location.BackgroundService")
class BackgroundService extends (<any>android).app.Service {
constructor() {
super();
return global.__native(this);
}
onStartCommand(intent, flags, startId) {
console.log('service onStartCommand');
this.super.onStartCommand(intent, flags, startId);
return android.app.Service.START_STICKY;
}
onCreate() {
console.log('service onCreate');
_startWatch();
}
onBind(intent) {
console.log('service onBind');
}
onUnbind(intent) {
console.log('service onUnbind');
}
onDestroy() {
console.log('service onDestroy');
_clearWatch();
}
}
return BackgroundService;
} else {
@JavaProxy("com.nativescript.location.BackgroundService26")
class BackgroundService26 extends (<any>android.app).job.JobService {
constructor() {
super();
return global.__native(this);
}
onStartJob(): boolean {
console.log('service onStartJob');
_startWatch();
return true;
}
onStopJob(jobParameters: any): boolean {
console.log('service onStopJob');
this.jobFinished(jobParameters, false);
_clearWatch();
return false;
}
}
return BackgroundService26;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.