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. 效果图