Service的使用

startService的生命周期

  1. onCreate
  2. onStartCommant
  3. onDestroy
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
fun start(v: View) {
    Intent(this, MyService::class.java).run {
        startService(this)
    }
}

fun stop(v: View) {
    Intent(this, MyService::class.java).run {
        stopService(this)
    }

    // or 在service中调用stopSelf()
}

这种方式创建Service,可以多次调用startService,并且onStartCommant方法也会随之回调,但是onCreate只会回调一次。

可以通过Intent向service传递信息。

当不需要service不需要继续运行时,需要手动关闭。

bindService的生命周期

  1. onCreate
  2. onBind
  3. onDestroy

Activity代码:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
private lateinit var service: MyService

/**
  *  自定义一个连接,用来获取service对象
  */
private val conn = object : ServiceConnection {
    override fun onServiceConnected(name: ComponentName?, binder: IBinder) {
        // 获取service
        val myBinder  = (binder as MyService.MyBinder)
        //调用业务方法
        myBinder.startDownload.invoke()
    }

    override fun onServiceDisconnected(name: ComponentName?) {
        // 当Service未正常退出,而是因为其他原因退出时回调
    }
}

fun bind(v: View) {
    Intent(this, MyService::class.java).run {
        bindService(this, conn, BIND_AUTO_CREATE)
    }
}

fun unbind(v: View) {
    Intent(this, MyService::class.java).run {
        unbindService(conn)
    }
}

Service代码:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
class MyService : Service() {

    /**
    * 预置一个自定义的binder
    **/
    private val mBinder = MyBinder {
        startDownload()
    }

    override fun onCreate() {
        Log.d(TAG, "onCreate: ")
        super.onCreate()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.d(TAG, "onStartCommand: ")
        return super.onStartCommand(intent, flags, startId)
    }

    override fun onBind(intent: Intent): IBinder {
        // 返回自定义的binder
        return mBinder
    }

    override fun onDestroy() {
        Log.d(TAG, "onDestroy: ")
        super.onDestroy()

    }

    /**
     * Activity可以直接通过service对象调用业务方法
     */
    private fun startDownload() {
        //处理下载任务,完成后通知Activity刷新UI
        mBinder.callback?.refreshUI()

    }

    /**
     * 自定义一个Binder内部类
     * 通过传递函数参数,实现Activity直接通过binder调用service的内部方法
     */
    inner class MyBinder(val startDownload: () -> Unit) : Binder() {

        var callback: MyBinderCallback? = null
    }
}

interface MyBinderCallback {
    fun refreshUI()
}