Android Service 极简总结

来源:互联网 发布:通达信 引用贝格数据 编辑:程序博客网 时间:2024/06/05 10:52
网遇一篇对Service的极简总结,初学android需要的就是这种点拨式的指导。博主略有强迫症,即使全篇粘贴也会将格式按照自己的标准重排,但是此文结构清晰的让人无法再优化了。

以下部分来源于Sina

  • Service是什么

a)      Service是一个应用程序组件

b)      Service没有图形化界面

c)      Service通常用来处理一些耗时比较久的操作

d)      可以使用Service更新ContentProvider,发送Intent以及启动系统的通知

等等

  • Service不是什么

a)      Service不是一个单独的进程

b)      Service不是一个线程

 

  • 实现Service

先继承Service,然后实现

onBind(),onCreate(),onStartCommand(),onDestroy()方法

然后要在AndroidMenifest.xml中进行注册:

<service>android:name=”.FirstService”></service>

    

  • Activity中如何启动Service

Intentintent = new Intent();

Intent.setClass(TestActivity.this,FirstService.class); 

startService(intent);

 

  • 关闭Service

Intentintent = new Intent();

Intent.setClass(TestActivity.this,FirstService.class);

StopService(intent);

    

  • Service的生命周期

当第一次创建一个service对象之后会首先调用onCreate(),然后调用onStartSCommand(),这个函数会得到intent对象,可以从intent对象中得到数据

 

此时再次开启service时,将不会调用onCreate()直接调用onStartCommand()

因为上一次service并没有销毁

 

当不想使用该service时,启动activity中的stopService()方法,系统就会调用service中的onDestroy()方法

0 0
原创粉丝点击