0
点赞
收藏
分享

微信扫一扫

安卓学习入门之IntentService基本使用方法

Sky飞羽 2022-02-27 阅读 34


简要介绍

Service是安卓的四大组件之一,常用来在后台执行一些耗时长的任务. 但是因为Service是运行在主线程的,如果要执行耗时任务则需要创建线程.而IntentService则是包含了内置线程的,用于简化任务的执行.IntentService的启动也分为startService和bindService两种方式,但是因为bindService方式跟Service无差别,所以一般不会对IntentService采用bindService方式.关于Service可以参考《安卓Service基本使用方法》

Service生命周期

安卓学习入门之IntentService基本使用方法_ide

使用方法


  • manifest文件中增加service定义
    ​<service android:name=".SampleIntentService" />​
  • 增加服务类SampleIntentService

class SampleIntentService : IntentService("worker_thread") {
private val tag = SampleIntentService::class.java.simpleName
override fun onHandleIntent(intent: Intent?) {
log(tag, "onHandleIntent")
doSomething()
}

private fun doSomething() {
log(tag, "doSomething")
Thread.sleep(2000)
}

override fun onCreate() {
log(tag, "onCreate")
super.onCreate()
}

override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
log(tag, "onStartCommand")
return super.onStartCommand(intent, flags, startId)
}

override fun onDestroy() {
log(tag, "onDestroy")
super.onDestroy()
}
}
  • activity调用
class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
startService(Intent(this, SampleIntentService::class.java))
}

}

Demo源代码

https://github.com/cxyzy1/intentServiceDemo

点击关注专栏,查看最新技术分享

更多技术总结好文,请关注:「程序园中猿」​​安卓学习入门之IntentService基本使用方法_生命周期_02​​​​安卓学习入门之IntentService基本使用方法_java_03​​

举报

相关推荐

0 条评论