当前位置: 首页 > news >正文

Service (一) 启动/绑定服务

1. 配置清单

  1.1 build.gradle 引用 lifecycle 库

dependencies {
    implementation 'androidx.lifecycle:lifecycle-service:2.6.0-alpha02'
    implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.6.0-alpha03'
    implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.6.0-alpha03'
} 

  1.2 AndroidManifest.xml 添加服务

      <service
            android:name=".MyService"
            android:enabled="true"
            android:exported="true" />

  1.3 配置第二个 Activity

    <activity
           android:name=".SecondActivity"
           android:exported="false">

2. 创建服务 MyService.kt

class MyService : LifecycleService() {
    private val mTAG = "MyTag"
    private var number = 0
    val numberLiveData = MutableLiveData(0)
    override fun onCreate() {
        super.onCreate()
        Log.i(mTAG, "onCreate: Service")
    }
    
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.i(mTAG, "onStartCommand: Service")
        //stopSelf()
        lifecycleScope.launch {
            while (true) {
                delay(1_000)
                Log.i(mTAG, "onStartCommand: ${number++}")
            }
        }
        return super.onStartCommand(intent, flags, startId)
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.i(mTAG, "onDestroy: Service")
    }

    inner class MyBinder : Binder() {
        val service = this@MyService
    }

    override fun onBind(intent: Intent): IBinder {
        super.onBind(intent)
        lifecycleScope.launch {
            while (true){
                delay(1_000)
                numberLiveData.value = numberLiveData.value?.plus(1)
            }
        }
        return MyBinder()
    }
}

3. 第一个Activity

  3.1 布局文件 activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:textSize="34sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.422" />

    <Button
        android:id="@+id/buttonStartService"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="68dp"
        android:text="StartService"
        android:textAllCaps="false"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent" />

    <Button
        android:id="@+id/buttonBindService"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="21dp"
        android:text="BindService"
        android:textAllCaps="false"
        app:layout_constraintBottom_toTopOf="@+id/buttonStartService"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <Button
        android:id="@+id/buttonStartActivity"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="32dp"
        android:text="Start Activity"
        android:textAllCaps="false"
        app:layout_constraintBottom_toTopOf="@+id/buttonBindService"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

  3.2 调用测试文件 MainActivity.kt

class MainActivity : AppCompatActivity() {
    private val mTAG = "MyTag"
    
    //1.用广播 容易破坏程序的结构化,不容易维护,容易滥用
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        Log.i(mTAG, "onCreate: AppCompatActivity")
    }

    override fun onStart() {
        super.onStart()
        Log.i(mTAG, "onStart: AppCompatActivity")
        val buttonStartService: Button = findViewById(R.id.buttonStartService)
        buttonStartService.setOnClickListener {
            Intent(this, MyService::class.java).also {
                //it.putExtra()
                startService(it)
            }
        }

        val buttonStartActivity:Button = findViewById(R.id.buttonStartActivity)
        buttonStartActivity.setOnClickListener {
            Intent(this,SecondActivity::class.java).also {
                startActivity(it)
            }
        }

        //BindService 用来返回服务器中的内容
        val buttonBindService: Button = findViewById(R.id.buttonBindService)
        val textView: TextView = findViewById(R.id.textView)
        buttonBindService.setOnClickListener {
            val bindIntent = Intent(this, MyService::class.java)
            val serviceConnection = object : ServiceConnection {
                override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
                    (service as MyService.MyBinder).service.numberLiveData.observe(this@MainActivity) {
                        textView.text = "$it"
                    }
                }

                override fun onServiceDisconnected(name: ComponentName?) {
                }
            }
            startService(bindIntent)
            bindService(bindIntent, serviceConnection, BIND_AUTO_CREATE)
        }
    }

    override fun onStop() {
        super.onStop()
//        Intent(this,MyService::class.java).also {
//            stopService(it)
//        }
        Log.i(mTAG, "onStop: AppCompatActivity")
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.i(mTAG, "onDestroy: AppCompatActivity")
    }
}

4. 第二个Activity

  4.1 布局文件 activity_second.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".SecondActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="164dp"
        android:text="TextView"
        android:textSize="34sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/buttonBindService"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="108dp"
        android:text="Bind Service"
        android:textAllCaps="false"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

  4.2 调用测试文件 SecondActivity.kt

class SecondActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_second)

        //BindService 用来返回服务器中的内容
        val buttonBindService: Button = findViewById(R.id.buttonBindService)
        val textView: TextView = findViewById(R.id.textView)
        buttonBindService.setOnClickListener {
            val bindIntent = Intent(this, MyService::class.java)
            val serviceConnection = object : ServiceConnection {
                override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
                    (service as MyService.MyBinder).service.numberLiveData.observe(this@SecondActivity) {
                        textView.text = "$it"
                    }
                }
                override fun onServiceDisconnected(name: ComponentName?) {
                }
            }
            bindService(bindIntent, serviceConnection, BIND_AUTO_CREATE)
        }
    }
}

5. 效果图

       

 

 

相关文章:

  • 效率倍增!5款超级好用的Python工具库!
  • 【QT开发笔记-基础篇】| 第五章 绘图QPainter | 5.2 界面布局
  • React组件设计模式-纯组件,函数组件,高阶组件
  • React的useLayoutEffect和useEffect执行时机有什么不同
  • 购物车服务-----技术点及亮点
  • 前端精准测试实践
  • 电力系统潮流【牛顿-拉夫逊法】(4节点、5节点、6节点、9节点)(Matlab代码实现)
  • java计算机毕业设计企业运营管理系统的设计与实现源程序+mysql+系统+lw文档+远程调试
  • PMP备考大全:经典题库(敏捷管理第10期)
  • OutOfMemory内存溢出问题排查
  • u-BOOT启动流程
  • 自动化运维场景在数据中心的落地之网络策略自动化管理-人保科技
  • akshare量化是如何精准分析的?
  • 日常学习之:Yaml 和 Json 有什么区别
  • Debezium系列之:支持数据库ddl和dml数据发往同一个Kafka Topic
  • 项目统一规范包管理器
  • 04 Vue 注册plgins的多种形式
  • 【C语言程序设计】实验 4
  • Java中Map集合体系的基本使用和常用API
  • 【在Vue脚手架项目中使用axios】
  • 电加热油锅炉工作原理_电加热导油
  • 大型电蒸汽锅炉_工业电阻炉
  • 燃气蒸汽锅炉的分类_大连生物质蒸汽锅炉
  • 天津市维修锅炉_锅炉汽化处理方法
  • 蒸汽汽锅炉厂家_延安锅炉厂家
  • 山西热水锅炉厂家_酒店热水 锅炉
  • 蒸汽锅炉生产厂家_燃油蒸汽发生器
  • 燃煤锅炉烧热水_张家口 淘汰取缔燃煤锅炉
  • 生物质锅炉_炉
  • 锅炉天然气_天燃气热风炉