Search code examples
androidkotlinandroid-intentservice

How to launch a service app from another app in Android?


I have a service app with no activity. I want to connect it with my main app, because I will send data from main app to service, then get response from it. Service should be launched programmatically.

If they was in same project, i could tag it in manifest like <service android:name.../> . I tried to intent but packageManager.getLaunchIntentForPackage also didn't work. Other apps with activity works with this way but service app is different.

Main App - Try to intent

val i = packageManager.getLaunchIntentForPackage("com.myexample.serviceapp")
if (i!=null) {
Log.d("MyService","Success")
startService(i)
} else {
Toast.makeText(this,"Fail",Toast.LENGTH_SHORT).show()
}

Main App - Manifest

<queries>
    <package android:name="com.myexample.serviceapp"/>
</queries>

Service App

class RegistryService : Service() {
    override fun onBind(p0: Intent?): IBinder? = null

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.d("MyService","working")

        Thread {
            while (true) {
                Log.d("MyService","working 2")
            }
        }.start()

        return START_STICKY
    }
}

Service Manifest

<service android:name=".RegistryService" />

Solution

  • It solve the problem.

    val i = Intent().apply {
                    this.setClassName("com.myexample.serviceapp", "com.myexample.serviceapp.RegistryService")
                }
                startForegroundService(i)