美文网首页安卓开发
安卓学习入门之IntentService基本使用方法

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

作者: 蓝不蓝编程 | 来源:发表于2019-04-09 19:19 被阅读4次

简要介绍

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

Service生命周期

使用方法

  • 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

安卓开发技术分享: https://www.jianshu.com/p/442339952f26
点击关注专辑,查看最新技术分享
更多技术总结好文,请关注:「程序园中猿」

相关文章

网友评论

    本文标题:安卓学习入门之IntentService基本使用方法

    本文链接:https://www.haomeiwen.com/subject/wcviiqtx.html