Kolone13
Kolone13

Reputation: 31

Starting a Service and referencing objects

i want to create a service in android studio which runs a client. I created my own serviceclass and i could start the service with

startService(new Intent(this,Client.class));

on my MainActivity. Now i want a reference object from the Client.class to the MainActivity. My problem is that there is no constructor. I don't want to do it static...

Upvotes: 0

Views: 154

Answers (2)

cincy_anddeveloper
cincy_anddeveloper

Reputation: 1152

This is intentional, you don't get a direct reference to your service. The Android framework takes care of starting and stop your services automatically. The same goes for Activities. If you need to perform actions on a Service there recommend practices is to send intents. If service is providing data for someone to consume you can use a broadcast receiver. If you want an actual object to directly execute methods on, you will need to make the service a bound one, and retrieve a binder object that will execute the calls on your behalf. It's a little more work involved but nothing difficult.

Here is a link to the Android documentation on Bound Services.

Upvotes: 1

DennisVA
DennisVA

Reputation: 2119

just use a setter. You can call the setter in an overidden onConnectionEstablished method provided by the ServiceConnection interface.

Read "Binding to a service" here: https://developer.android.com/guide/components/bound-services

Upvotes: 0

Related Questions