目录
10.3 Service的基本用法
了解了 Android 多线程编程的技术之后,下面就让我们进入本章的正题,开始对 Service 的相关内容进行学习。作为 Android 四大组件之一,Service 也少不了有很多非常重要的知识点,那我 们自然要从最基本的用法开始学习了。
10.3.1 定义一个Service
首先看一下如何在项目中定义一个 Service 。新建一个 ServiceTest 项目,然后右击 com.example.servicetest→New→Service→Service ,会弹出如图10.4 所示的窗口。
![](https://i-blog.csdnimg.cn/blog_migrate/0084855323bf24dbc53bde4609428ff0.png)
可以看到,这里我们将类名定义成 MyService ,Exported 属性表示是否将这个 Service 暴露给外部其他程序访问,Enabled 属性表示是否启用这个Service 。将两个属性都勾中,点击“Finish” 完成创建。
现在观察 MyService 中的代码,如下所示:
class MyService : Service() {
override fun onBind(intent: Intent): IBinder {
TODO("Return the communication channel to the service.")
}
}
可以看到,MyService 是继承自系统的 Service 类的。目前 MyService 中可以算是空空如也, 但有一个 onBind() 方法特别醒目。这个方法是 Service 中唯一的抽象方法,所以必须在子类里 实现。我们会在后面的小节中使用到 onBind() 方法,目前可以暂时将它忽略。
既然是定义一个 Service ,自然应该在 Service 中处理一些事情了,那处理事情的逻辑应该写在哪里呢?这时就可以重写 Service 中的另外一些方法了,如下所示:
class MyService : Service() {
override fun onBind(intent: Intent): IBinder {
TODO("Return the communication channel to the service.")
}
// 服务创建时调用
override fun onCreate() {
super.onCreate()
}
// 服务启动时调用
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
return super.onStartCommand(intent, flags, startId)
}
// 服务销毁时调用
override fun onDestroy() {
super.onDestroy()
}
}
可以看到,这里我们又重写了 onCreate()、onStartCommand() 和 onDestroy() 这3个方 法,它们是每个 Service 中最常用到的 3 个方法了。其中 onCreate() 方法会在 Service 创建的时候调用,onStartCommand() 方法会在每次 Service 启动的时候调用,onDestroy() 方法会在Service 销毁的时候调用。
通常情况下,如果我们希望Service 一旦启动就立刻去执行某个动作,就可以将逻辑写在 onStartCommand() 方法里。而当Service 销毁时,我们又应该在 onDestroy() 方法中回收 那些不再使用的资源。
另外需要注意,每一个 Service 都需要在 AndroidManifest.xml 文件中进行注册才能生效。不 知道你有没有发现,这是 Android 四大组件共有的特点。不过相信你已经猜到了,智能的 Android Studio 早已自动帮我们完成了。打开 AndroidManifest.xml 文件瞧一瞧,代码如下所 示:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.servicetest">
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.ServiceTest"
tools:targetApi="31">
<service
android:name=".MyService"
android:enabled="true"
android:exported="true">
</service>
<activity
android:name=".MainActivity"
android:exp