fragment中绑定服务



package com.lyr.myapplication.service


import android.content.Intent
import android.os.Binder
import android.os.IBinder
import android.util.Log
import androidx.lifecycle.LifecycleService
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class ExampleService : LifecycleService() {
     val number: MutableLiveData<Int> = MutableLiveData(0)
    override fun onCreate() {
        super.onCreate()

        Log.i("xxx", "开启服务")
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {

        lifecycleScope.launch{
            while (true) {
                delay(1_000)
//                Log.d("xx","${++number}")
            }
        }


        return super.onStartCommand(intent, flags, startId)

    }

    inner class ExampleBinder : Binder() {
        val service:ExampleService = this@ExampleService
    }

    override fun onBind(intent: Intent): IBinder {
        super.onBind(intent)

        lifecycleScope.launch{
            while (true) {
                delay(1_000)
                number.value = number.value?.plus(1)
            }

        }
        return ExampleBinder()
    }
}

fragment 代码:


package com.lyr.myapplication

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import com.lyr.myapplication.service.ExampleService
import kotlinx.android.synthetic.main.fragment_blank1.*

// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

/**
 * A simple [Fragment] subclass.
 * Use the [BlankFragment1.newInstance] factory method to
 * create an instance of this fragment.
 */
class BlankFragment1 : Fragment() {
    // TODO: Rename and change types of parameters

    override fun onCreate(savedInstanceState: Bundle?) {
        Log.i("xx", "fragment create")
        super.onCreate(savedInstanceState)

//        Intent

//        activity?.startService(Intent(activity, ExampleService::class.java))


        val intent = Intent(this.activity, ExampleService::class.java)

        val serviceConnection = object : ServiceConnection {

            val at = activity as ExampleActivity
            override fun onServiceDisconnected(name: ComponentName?) {

            }


            override fun onServiceConnected(name: ComponentName?, service: IBinder?) {

                (service as ExampleService.ExampleBinder).service
                    .number.observe(at, Observer {
                        f1_text.text = "$it"
                    })
                Log.i("xxoo", "绑定服务了OK")


            }
        }



        activity?.bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE)


    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_blank1, container, false)
    }

    companion object {
        /**
         * Use this factory method to create a new instance of
         * this fragment using the provided parameters.
         *
         * @param param1 Parameter 1.
         * @param param2 Parameter 2.
         * @return A new instance of fragment BlankFragment1.
         */
        // TODO: Rename and change types and number of parameters
        @JvmStatic
        fun newInstance(param1: String, param2: String) =
            BlankFragment1().apply {
                arguments = Bundle().apply {
                    putString(ARG_PARAM1, param1)
                    putString(ARG_PARAM2, param2)
                }
            }
    }
}

多次调用startService,该Service只能被创建一次,即该Service的onCreate方法只会被调用一次。但是每次调用startService,onStartCommand方法都会被调用。Service的onStart方法在API 5时被废弃,替代它的是onStartCommand方法。

第一次执行bindService时,onCreate和onBind方法会被调用,但是多次执行bindService时,onCreate和onBind方法并不会被多次调用,即并不会多次创建服务和绑定服务。

如果要和 服务通信,需要使用 bindservice 的方法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值