Sobes.tech
Middle

Kā organizējat mijiedarbību starp fragmentu un pakalpojumu jūsu lietojumprogrammā?

sobes.tech AI

Atbilde no AI

Galvenie veidi, kā mijiedarbojas fragments un pakalpojums, ir šādi:

  • Saistīts pakalpojums (Bound Service): fragments pieslēdzas pakalpojumam un tieši piekļūst publiskajām metodēm, izmantojot IBinder saskarni.
  • Sāktā pakalpojums (Started Service): fragments sāk pakalpojumu, nosūtot Intent ar datiem. Atgriezeniskajai saitei pakalpojums var sūtīt plašsaziņas līdzekļu Intent vai izmantot ResultReceiver.
  • Plašsaziņas līdzekļu Intent (BroadcastReceiver): Pakalpojums sūta plašsaziņas līdzekļu Intent, kurus fragments klausās, izmantojot BroadcastReceiver.
  • Notikumu autobuss (piemēram, GreenDao EventBus, Otto): Izmanto notikumu apmaiņai starp komponentiem caur centrālo pārvaldnieku. Pakalpojums publicē notikumus, bet fragments tiem piesakās.
  • LiveData: fragments var novērot LiveData objektu ViewModel, kas savukārt mijiedarbojas ar pakalpojumu (piemēram, caur repozitoriju vai tiešu metožu izsaukumu).

Izvēloties metodi, ņem vērā:

  • Pakalpojuma veidu (saistīts vai sāktas).
  • Divvirzienu mijiedarbības nepieciešamību.
  • Pārsūtāmo datu sarežģītību.
  • Fragmenta un pakalpojuma dzīves ciklu.
  • Koda lasāmību un uzturēšanu.

Piemērs, kā sasaistīt fragmentu ar pakalpojumu:

// Fragment
private lateinit var myService: MyService
private var isBound = false

private val connection = object : ServiceConnection {
    override fun onServiceConnected(className: ComponentName, service: IBinder) {
        val binder = service as MyService.LocalBinder
        myService = binder.getService()
        isBound = true
    }

    override fun onServiceDisconnected(arg0: ComponentName) {
        isBound = false
    }
}

override fun onStart() {
    super.onStart()
    Intent(requireContext(), MyService::class.java).also { intent ->
        requireContext().bindService(intent, connection, Context.BIND_AUTO_CREATE)
    }
}

override fun onStop() {
    super.onStop()
    if (isBound) {
        requireContext().unbindService(connection)
        isBound = false
    }
}

Piemērs, kā sūtīt plašsaziņas līdzekļu Intent no pakalpojuma:

// Pakalpojums
private fun sendUpdate(data: String) {
    Intent("my.app.SERVICE_UPDATE").apply {
        putExtra("data", data)
    }.also { intent ->
        sendBroadcast(intent)
    }
}

Piemērs, kā pieņemt plašsaziņas līdzekļu Intent fragmentā:

// Fragment
private val receiver = object : BroadcastReceiver() {
    override fun onReceive(context: Context?, intent: Intent?) {
        when (intent?.action) {
            "my.app.SERVICE_UPDATE" -> {
                val data = intent.getStringExtra("data")
                // Datu apstrāde
            }
        }
    }
}

override fun onResume() {
    super.onResume()
    IntentFilter("my.app.SERVICE_UPDATE").also { filter ->
        requireContext().registerReceiver(receiver, filter)
    }
}

override fun onPause() {
    super.onPause()
    requireContext().unregisterReceiver(receiver)
}