Android Service

Android 的四大组件:Activity,Service,BroadcastReceiver,ContentProvider
Service:一个运行在后台的组件,执行长时间运行且不需要与用户交互的任务。我们可以通过继承Service类来实现自定义Service。

class MyTestService : Service() {
    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    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()
    }
}

Service组件跟Activity组件一样在使用前需要在manifest文件中进行声明

  <service
            android:name=".services.MyTestService"
            android:exported="true|false" 
            android:process=":testProcess" />

android:name 对应自定义的Service的类名
android:exported 代表Service是否能被其他应用隐式调用,其默认值是由service中有没有intent-filter决定的,如有则为true,否则为false。手动设置为false的情况下,即使intent-filter有匹配也无法开启服务,即表示无法被其他应用隐式调用。
android:process 用于设置Service所运行的进程

Service有两种启动方式,startService,bindService

startService

其他组件可以通过startService()的方式启动,一旦启动则在后台无限期运行,即便启动它的组件已经被销毁。(当内存不足时也会存在被清理的风险)
生命周期:onCreate---->onStartCommand---->onDestory

bindService

其他组件可以通过bindService()的方式启动,
生命周期:onCreate---->onBind---->onUnbind---->onDestory

image.png

详细内容可参照
https://blog.csdn.net/javazejian/article/details/52709857

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容