ForegroundServiceとActivityの連携

2021/02/05
Android
ForegroundService

Androidアプリ開発において、ForegroundServiceをbindServiceして手軽に連携する方法です。

環境

  • compileSdkVersion 29
  • minSdkVersion 21

方法

startServiceでStartedになったServiceにも普通にbind可能です。なので、ForegroundなService起動直後にbindServiceするとbindされたForegroundServiceが得られます。
Activity起動時にServiceが既に起動している可能性があるので、起動していたらbindするという処理が必要ですね。起動確認に関しては以下にあります。

Serviceが起動しているか確認する

class SomeActivity : AppCompatActivity() {

    private lateinit var boundService: SomeService
    private var isBoundService: Boolean = false

    private val serviceConnection = object: ServiceConnection{

        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            loggerService = (service as SomeService.LocalBinder).getService()
            isBoundService = true
        }

        override fun onServiceDisconnected(name: ComponentName?) {
            isBoundService = false
        }

    }

    private fun bindSomeService(){
        Intent(this, SomeService::class.java).also { intent ->
            bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE)
        }
    }

    private fun startSomeService(){
        Intent(this, SomeService::class.java).also { intent ->
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                startForegroundService(intent)
            }
            else{
                startService(intent)
            }
        }
    }

    private fun unbindSomeService(){
        if(isBoundService){
            unbindService(serviceConnection)
        }
    }

    private fun stopSomeService(){
        Intent(this, SomeService::class.java).also { intent ->
            stopService(intent)
        }
    }

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

        //  service開始ボタン
        findViewById<Button>(R.id.start_service).also { button ->
            button.setOnClickListener {
                //  start直後にbind
                startSomeService()
                bindSomeService()
            }
        }

        //  service終了ボタン
        findViewById<Button>(R.id.stop_service).also { button ->
            button.setOnClickListener {
                unbindSomeService()
                stopSomeService()
            }
        }

        if(SomeService.isActive(this)){
            bindLoggerService()
        }
    }
}

© 2019-2022 hassakulab.com, built with Gatsby