关于Service介绍
实现需求
Tips:先赞后看,人生灿烂!
第一步:首先创建一个Service
在onStartCommand()方法中我只让它弹个吐司,表明服务启动了
/**
* @data on 4/27/21 10:03 AM
* @auther KC
* @describe 定义一个简单的服务
*/
class ExampleService : Service() {
private var startMode: Int = 0 // indicates how to behave if the service is killed
private var binder: IBinder? = null // interface for clients that bind
private var allowRebind: Boolean = false // indicates whether onRebind should be used
override fun onCreate() {
// The service is being created
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
// The service is starting, due to a call to startService()
Toast.makeText(this,"Service starting ...",Toast.LENGTH_SHORT).show()
return startMode
}
override fun onBind(intent: Intent): IBinder? {
// A client is binding to the service with bindService()
return binder
}
override fun onUnbind(intent: Intent): Boolean {
// All clients have unbound with unbindService()
return allowRebind
}
override fun onRebind(intent: Intent) {
// A client is binding to the service with bindService(),
// after onUnbind() has already been called
}
override fun onDestroy() {
// The service is no longer used and is being destroyed
}
}
第二步:在AndroidManifest.xml文件中引入该ExampleService
提及一下exported这个属性,是指定该Service是否被其他app可以获取,这里的false就是指明,只有当前app可以获取到,不能被其他app获取。
<application>
...
<service
android:name=".service.ExampleService"
android:exported="false" />
...
</application>
第三步:在Activity中处理逻辑
布局中三个按钮,点击分别代表:开启服务、判断是否开启服务、关闭服务。
主要用AM的getRunningSercices方法,来拿到系统中该app正在运行的Service列表,然后遍历它,看是否Service列表中的Name值是否包含ServiceName。
@Route(path = RouterPath.kotlin15)
class Kotlin15 : AppCompatActivity() {
val intentExample by lazy { //延迟初始化
Intent(this, ExampleService::class.java)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//绑定布局
val vBinding = ActivityKotlin15Binding.inflate(layoutInflater)
setContentView(vBinding.root)
//点击事件
vBinding.openService.setOnClickListener {
startService(intentExample) //开启服务
}
vBinding.closeService.setOnClickListener {
stopService(intentExample) //关闭服务
}
vBinding.isOpenService.setOnClickListener {
Toast.makeText(
this,
isOpenedService(this, "ExampleService").toString(),
Toast.LENGTH_SHORT
).show()
}
}
//判断是否app开启了某个Service
private fun isOpenedService(mContext: Context, className: String): Boolean {
var isRunning = false;
val systemService : ActivityManager = mContext.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
val serviceList: List<ActivityManager.RunningServiceInfo> = systemService
.getRunningServices(30)
if (serviceList.isEmpty()) {
return false;
}
serviceList.forEach {
if (it.service.className.contains(className)){
isRunning = true
}
}
return isRunning;
}
}
网友评论