Reputation: 347
I need to implement a Background Service in NativeScript which will get user location each x minutes, make a request to my API, and depending on the response, emit a local notification.
So I started searching for ways to implement this, which led me to this NativeScript repository. As stated in the README:
The current implementation utilizes the NotificationChannel, which was added in API Level 26. If you want to target lower API Levels, take a look at the older implementation Alarm Manager Implementation. Have in mind, that this approaches is not supported with API Level 26 or newer due to limitations in the OS.
I need to support Android 5.1+ (API Level 22+), so the new implementation will not work for me, instead, I should use the older Alarm Manager Implementation as mentioned. The problem is, as you can see in the quote, this approach is not supported with API Level 26+.
And as everyone knows, Google is forcing new apps to target at least API Level 28. So, how can I implement a Background Service which will work from API Level 22 to 28?
Upvotes: 1
Views: 635
Reputation: 21908
You may refer to the example in the nativescript-geolocation plugin repo, works for all supported versions of 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;
}
Upvotes: 3