OhMad
OhMad

Reputation: 7289

Run Service in the background

I am very new to Android Development and I don't really get how IntentServices work. This is what I have so far:

class TimerActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_timer)

        findViewById(R.id.startBtn).setOnClickListener {
            startService(Intent(this@TimerActivity, TimerService::class.java))
        }

        findViewById(R.id.stopBtn).setOnClickListener {
            stopService(Intent(this@TimerActivity, TimerService::class.java))
        }
    }
}

class TimerService : IntentService("TimerService") {

    override fun onCreate(){
        super.onCreate()
        toast("Started activity")
    }

    override fun onDestroy(){
        super.onDestroy()
        toast("Stopped activity")
    }

    override fun onHandleIntent(intent: Intent?) {

    }
}

I am trying to start an activity in the background on the click of a button, and stop it on the click of the other one. But why does onDestroy() get triggered right after onCreate(), without me clicking on the stop button?

Thanks

Upvotes: 0

Views: 1184

Answers (1)

tynn
tynn

Reputation: 39843

That's how IntentService works.

IntentService is a base class for Services that handle asynchronous requests (expressed as Intents) on demand. [...]

[...] IntentService will receive the Intents, launch a worker thread, and stop the service as appropriate.

All requests are handled on a single worker thread -- they may take as long as necessary (and will not block the application's main loop), but only one request will be processed at a time.

The service will be alive as long as there are tasks to process. After that the service will end and restart with the next task.

If you want to have a running service, possibly even a bound service, you have to subclass Service directly and take care of the threading

Caution: A service runs in the same process as the application in which it is declared and in the main thread of that application by default. If your service performs intensive or blocking operations while the user interacts with an activity from the same application, the service slows down activity performance. To avoid impacting application performance, start a new thread inside the service.

and the life-time

Caution: To avoid wasting system resources and consuming battery power, ensure that your application stops its services when it's done working. If necessary, other components can stop the service by calling stopService(). Even if you enable binding for the service, you must always stop the service yourself if it ever receives a call to onStartCommand().

Upvotes: 1

Related Questions