TestService.kt
package com.example.kotlingradletemplatefirst.service
import android.app.Service
import android.content.Intent
import android.os.Binder
import android.os.IBinder
import android.util.Log
class TestService : Service() {
private var count: Int = 0
private var quit = false
private var binder = MyBinder()
inner class MyBinder : Binder() {
fun getCount(): Int {
return this@TestService.count
}
}
override fun onBind(p0: Intent?): IBinder {
"""
功能:实现接口方法
""".trimIndent()
Log.e("TestService", "onBind")
return binder
}
override fun onUnbind(intent: Intent?): Boolean {
Log.e("TestService", "onUnbind")
return super.onUnbind(intent)
}
override fun onCreate() {
super.onCreate()
Log.e("TestService", "onCreate")
object : Thread() {
override fun run() {
while (!quit) {
println("定时器执行中...")
try {
sleep(1000)
} catch (e: InterruptedException) {
e.printStackTrace()
}
this@TestService.count++
}
}
}.start()
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
Log.e("TestService", "onStartCommand")
return super.onStartCommand(intent, flags, startId)
}
override fun onDestroy() {
super.onDestroy()
Log.e("TestService", "onDestroy")
// 销毁时必须退出while循环!
this.quit = true
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:id="@+id/start_service"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:backgroundTint="#00f"
android:text="startService"
android:textAllCaps="false" />
<Button
android:id="@+id/get_binder_data"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:backgroundTint="#0f0"
android:text="getBinderData"
android:textAllCaps="false" />
<Button
android:id="@+id/check_service_status"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:backgroundTint="#f0f"
android:text="checkServiceStatus"
android:textAllCaps="false" />
<Button
android:id="@+id/stop_service"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:backgroundTint="#f00"
android:text="stopService"
android:textAllCaps="false" />
</LinearLayout>
MainActivity.kt
package com.example.kotlingradletemplatefirst
import android.app.ActivityManager
import android.app.Service
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.widget.Button
import androidx.appcompat.app.AppCompatActivity
import com.example.kotlingradletemplatefirst.service.TestService
class MainActivity : AppCompatActivity() {
private var binder: TestService.MyBinder? = null
private var conn: ServiceConnection? = null
private var componentName: ComponentName? = null
private var isBinder: Boolean = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val intent = Intent(this, TestService::class.java)
println("TestService::class.java=${TestService::class.java.name}")
this.conn = object : ServiceConnection {
override fun onServiceConnected(p0: ComponentName?, p1: IBinder?) {
Log.e("MainActivity", "onServiceConnected")
/**
* 1、连接成功,会返回绑定的binder对象!
*/
this@MainActivity.binder = (p1 as TestService.MyBinder)
}
override fun onServiceDisconnected(p0: ComponentName?) {
Log.e("MainActivity", "onServiceDisconnected")
}
}
findViewById<Button>(R.id.start_service).setOnClickListener {
/**
* 1、启动或绑定Service
* 2、如果是startService,则必须手动调用stopService
* 3、如果是bindService,则必须手动调用unbindService
*/
// this.componentName = startService(intent)
this.isBinder = bindService(intent, this.conn!!, Service.BIND_AUTO_CREATE)
}
findViewById<Button>(R.id.stop_service).setOnClickListener {
/**
* 1、停止或解绑服务!
*/
// if (this.componentName != null) {
// stopService(intent)
// this.componentName = null
// }
if (this.isBinder) {
unbindService(this.conn!!)
this.isBinder = false
}
}
findViewById<Button>(R.id.check_service_status).setOnClickListener {
/**
* 功能:检测Service是状态【是否已启动】
* 特殊说明:
* 1、getRunningServices仅支持【API level 26以下版本】
* 2、26以上版本请参考:https://blog.csdn.net/weixin_43343144/article/details/129690608
*/
val manager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
val runningServices = manager.getRunningServices(Integer.MAX_VALUE)
var num = 0
for (service in runningServices) {
if (TestService::class.java.name == service.service.className) {
// MyService 已经启动
Log.e("MainActivity", "service=${TestService::class.java.name} is Starting...")
num++
}
}
Log.e("MainActivity", "service=${TestService::class.java.name}的启动的个数为【$num】")
}
findViewById<Button>(R.id.get_binder_data).setOnClickListener {
/**
* 1、获取Service绑定的数据
*/
Log.e("MainActivity", "count=${this.binder?.getCount()}")
}
}
}