started service

创建一个开始的服务:

一个开始的服务被启动当另一个组件通过调用startService()。然后这个服务调用onStartCommand()方法。当一个服务被启动了,它的是独立于启动它的组件的。这个服务将一直运行于后台,甚至启动它的组件被销毁。同样的,这个服务能停止他自己当它的任务完成,通过调用stopSelf()。或者另一些组件也能停止它,通过调用 stopService()

一个应用组件比如一个activity能开始一个服务通过调用 startService(),通过Intent去指定这个服务包括传递的数据。这个服务将会接受到Intent在 onStartCommand()方法里。

例如,假如一个activity需要保存一些数据到在线数据库中,这个activity能开始一个服务,传递它的数据去保存通过Intent的 startService()方法。这个服务接受到这个Intent在 onStartCommand()方法中,然后连接到Intent,执行数据库的保存事务。当这个任务做完,这个服务将自动被销毁。

传统上,你能基础两个类去创建一个开始的服务。

Service

这是一个基础的services类,当你继承这个类,非常重要的是你创建一个新的线程去做所有的service的工作。因为这个service是再你的主线程中的,默认情况下,你的应用程序运行的会比较慢的。所以非常有必要在service中创建一个新的线程去执行service的任务。

IntentService

这是一个service的子类,使用一个工作的线程去处理所以的开始请求,每次一个。这是一个最好的选择如果你不要求你的服务同时处理多个请求。你必须去实现 onHandleIntent()方法,这个方法是去接受每一个Intent的请求,因此你可以做后台的工作。


继承IntentService类

因为许多开启的服务不需要去同时执行多个请求,所以它可能是最好的如果你实现你的service用IntentService类。

这而是一个实现了IntentService得例子:

public class HelloIntentService extends IntentService { /** * A constructor is required, and must call the super IntentService(String) * constructor with a name for the worker thread. */ public HelloIntentService() { super("HelloIntentService"); } /** * The IntentService calls this method from the default worker thread with * the intent that started the service. When this method returns, IntentService * stops the service, as appropriate. */ @Override protected void onHandleIntent(Intent intent) { // Normally we would do some work here, like download a file. // For our sample, we just sleep for 5 seconds. long endTime = System.currentTimeMillis() + 5*1000; while (System.currentTimeMillis() < endTime) { synchronized (this) { try { wait(endTime - System.currentTimeMillis()); } catch (Exception e) { } } } } } 上面的构造器和 onHandleIntent()方法是必须得。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值