什么是IntentService
IntentService是为简化Service使用而生的.Service的执行默认是在主线程中,一般都需要另外再创建线程来执行任务,而使用IntentService就省去了自己创建线程的工作.
创建IntentService
-
在工程目录中单击右键,选择“New>Service>Service(IntentService)”
-
在窗口中设置IntentService名称(其他设置保持默认即可)
- 创建后的IntentService比较繁杂,此处就不列出了.
- 查看AndroidManifest.xml文件,里面应该已经增加了如下Service配置.
<manifest ...>
<application ...>
<service
android:name=".MyIntentService"
android:exported="false"></service>
...
</application>
</manifest>
启动Service样例
- Service代码:MyIntentService.kt
class MyIntentService : IntentService("MyService") {
override fun onHandleIntent(intent: Intent?) {
Log.d("MyService", "onHandleIntent")
study()
}
private fun study() {
for (index in 1..10) {
Log.d("MyService", "我在学习,我在学习,没偷懒")
Thread.sleep(2000)
}
}
override fun onCreate() {
Log.d("MyService", "onCreate")
super.onCreate()
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
Log.d("MyService", "onStartCommand")
return super.onStartCommand(intent, flags, startId)
}
override fun onDestroy() {
Log.d("MyService", "onDestroy")
super.onDestroy()
}
}
- 调用代码
class MainActivity : AppCompatActivity() {
private lateinit var serviceIntent: Intent
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//启动Service
serviceIntent = Intent(this, MyIntentService::class.java)
startService(serviceIntent)
}
override fun onDestroy() {
super.onDestroy()
//停止Service
stopService(serviceIntent)
}
}
网友评论