14

By using the below code, I'm trying to start new service from a Broadcast receiver, but the service does not seem to start. What is the correct way to start a service in kotlin?

val intent = Intent(context, LocationService::class.java)
 if (context != null) {
      context.startService(intent)
 }
Rahul
  • 3,293
  • 2
  • 31
  • 43
Logo
  • 1,366
  • 2
  • 11
  • 16
  • Is the service registered in the manifest? – shelll Aug 09 '17 at 08:54
  • 1
    Make sure that `startService` returns non-null value, this will indicate that service was started. Keep in mind that `startService` is deprecated in Android O and will throw exception for `targetSdk 26`. – Miha_x64 Aug 09 '17 at 09:15

4 Answers4

16

try this

 val intent = Intent(context, LocationService::class.java)
 if (context != null) {
      context.startService(intent)
 }

And don't forget to register your service in manifest file

 <service  android:name="packageName.LocationService"/>
Nigam Patro
  • 2,760
  • 1
  • 18
  • 33
AskNilesh
  • 67,701
  • 16
  • 123
  • 163
5

Use safe access compression in kotlin:

val intent = Intent(context, LocationService::class.java)
context?.startService(intent)

Also define your service in your manifest.

Anice Jahanjoo
  • 7,088
  • 3
  • 20
  • 29
1

Put declaration of service in AndroidManifest.xml file
i.e <service android:name=".LocationService"/>

mac229
  • 4,319
  • 5
  • 18
  • 24
1

You need to declare your service in AndroidManifest.xml

<manifest ...>
   <application ...>
      <service
          android:name="package.LocationService">
      </service>
   </application>
</manifest>