`
chenpeilei2003
  • 浏览: 187283 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

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);

 

 

 

 

 

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics