Android service简单整理

一、什么时候绑定,什么时候不绑定?

当 Activity 需要与 Service 通信时,要通过绑定来进行通信。广播也可以但效率较低根据实际情况定

最简单的场景就是后台做一些定时任务,不绑定直接启动就用了

二、

用法

<service

            android:name="这里是名称"

            android:exported="false"

 </service>

在 Activity 里启动

Intent intent = new Intent(this,  MyService.class);

startService(intent);

这种方式下由于没有绑定客户端,只能退出程序时自动停止或者 stopSelf(),无须手动 stop.

适用于数据里较大较耗时的初始化工作、一些后台的轮询任务等。

 

如果希望程序退出后服务还能继续,修改配置

<service

            android:name="这里是名称"

            android:exported="false"

            android:enabled="true"

            android:process="system"

 </service>

            在启动的时候加入标记intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

 

 

 

 

猜你喜欢

转载自chenpeilei2003.iteye.com/blog/2247195