目录
1.Service
Service启动后默认是运行在主线程中,在执行具体耗时任务过程中要手动开启子线程
2.Service生命周期
3.创建Service
3.1普通启动startService()
- 编写自己的Service且继承Service类
- 在AndroidMainfest中注册编写的Service
- 在需要启动的Activity中StartService启动服务
import android.app.Service
import android.content.Intent
import android.os.IBinder
import android.util.Log
class MyService : Service() {
private val TAG = "MyService"
//必须要实现的方法
override fun onBind(intent: Intent): IBinder?{
Log.e(TAG, "onBind方法被调用!")
return null
}
//Service被创建时调用
override fun onCreate() {
Log.e(TAG, "onCreate方法被调用!")
super.onCreate()
}
//Service被启动时调用
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
Log.e(TAG, "onStartCommand方法被调用!")
return super.onStartCommand(intent, flags, startId)
}
//Service被关闭之前回调
override fun onDestroy() {
Log.e(TAG, "onDestory方法被调用!")
super.onDestroy()
}
}
AndroidMainfest中注册Service:
<service
android:name=".MyService"
android:enabled="true"
android:exported="true"></service>
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
Log.i("Activity生命周期","onCreate方法调用,第一次创建时进行调用")
val button=findViewById<View>(R.id.button2)
button.setOnClickListener{
val intent = Intent(this,MyService::class.java);
startService(intent);
}
}
}
3.2启动bindService()
步骤同创建普通启动startService()
import android.app.Service
import android.content.Intent
import android.os.Binder
import android.os.IBinder
import android.util.Log
class BinderService : Service() {
private val TAG = "BinderService"
private var count = 0
private var quit = false
private val binder: MyBinder = MyBinder()
//创建内部类
inner class MyBinder : Binder() {
fun getCount(): Int {
return count
}
}
override fun onBind(intent: Intent): IBinder {
Log.e(TAG, "onBind方法被调用!")
return binder
}
//Service被创建时回调
override fun onCreate() {
super.onCreate()
Log.e(TAG, "onCreate方法被调用!")
//创建一个线程动态地修改count的值
object : Thread() {
override fun run() {
while (!quit) {
try {
sleep(1000)
} catch (e: InterruptedException) {
e.printStackTrace()
}
count++
}
}
}.start()
}
//Service断开连接时回调
override fun onUnbind(intent: Intent?): Boolean {
Log.i(TAG, "onUnbind方法被调用!")
return true
}
//Service被关闭前回调
override fun onDestroy() {
super.onDestroy()
quit = true
Log.i(TAG, "onDestroyed方法被调用!")
}
override fun onRebind(intent: Intent?) {
Log.i(TAG, "onRebind方法被调用!")
super.onRebind(intent)
}
}
AndroidMainfest中注册Service:
<service
android:name=".BinderService"
android:enabled="true"
android:exported="true"></service>
<service
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.IBinder
import android.util.Log
import android.view.View
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_my)
var binder=BinderService().MyBinder()
val conn: ServiceConnection = object : ServiceConnection {
//Activity与Service断开连接时回调该方法
override fun onServiceDisconnected(name: ComponentName) {
println("------Service DisConnected-------")
}
//Activity与Service连接成功时回调该方法
override fun onServiceConnected(name: ComponentName, service: IBinder) {
println("------Service Connected-------")
binder = service as BinderService.MyBinder
}
}
// bind服务
val intent = Intent(this,BinderService::class.java)
bindService(intent,conn, Context.BIND_AUTO_CREATE)
val start_service=findViewById<View>(R.id.start)
start_service.setOnClickListener {
// 从服务获取数据
Log.e("BinderService","getCount:${binder?.getCount()}")
}
// 停止按钮
val stop_service=findViewById<View>(R.id.stop)
stop_service.setOnClickListener {
unbindService(conn)
}
}
}
布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<Button
android:id="@+id/start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="启动" />
<Button
android:id="@+id/stop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="停止" />
</LinearLayout>