How to start android background service in typescript


#1

Hello,

I’m trying to create android background service by using typescript.

So far I have following service class:

@JavaProxy("com.somepackage.MyService")
export class MyService extends android.app.Service {

    public onStartCommand(intent, flags, startId) {
        console.log('MyService start')
        this.onStartCommand(intent, flags, startId);
        return android.app.Service.START_STICKY;
    }

    public onCreate() {
        var count = 0
        console.log('MyService create')
        const id = timer.setInterval(() => {
            count++
            console.log('timer ticks:' + count)
        }, 1000);
    }

}

In android manifest I have:

<service android:name="com.somepackage.MyService" android:exported="false" >

Problem is that I don’t know how to refer service correctly when I want to start it. I’m currently trying to start service like this but compiler does not recognize class package.

export function startWorker() {
    console.log('starting worker...')
    let context = application.android.context
    var intent = new android.content.Intent(context, com.somepackage.MyService.class)
    context.startService(intent);
}

#2

This doesn’t answer your question directly, but have you seen nativescript’s wrapper for workers? Maybe it does what you’re trying to accomplish.


#3

I tried worker first but in my test it stopped execution when app goes to background.


#4

Just to update that I managed to get android background service to work.

Needs additionally this utils package: https://github.com/Pip3r4o/nativescript-android-utils

Service:

declare var com: any

@JavaProxy("com.foo.MyService")
export class MyService extends com.pip3r4o.android.app.IntentService {

    protected onHandleIntent(intent: android.content.Intent): void {
        console.log('executing service')
    }

   
}

JavaProxy service name needs to be added to android manifest:

<service android:name="com.foo.MyService" android:exported="false"/>

Starting service:

function startBackgroundService() {
    let context = application.android.context
    var intent = new android.content.Intent()
    intent.setClassName(context, "com.foo.MyService")
    context.startService(intent);
}