浅谈Service
来源:互联网 发布:进度计划编制软件 编辑:程序博客网 时间:2024/06/05 11:07
Android Service(服务)
一、前言
二、正文
context.startService() -> onCreate() -> OnStartCommand()或者(onStart()) -> Service running -> context.stopService() -> onDestroy() -> Service stop
注:
A、 OnStratCommand()是在android2.0(API-5)以后引入的代替掉onStart事件。虽然他们提供的功能一样。但是使用onStart()启动,它返回的值会控制当Service被运行时终止后,系统应该如何响应Service的重新启动。
再次我要说一下,执行一个Service并控制它的重新启动行为。
@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {// TODO Auto-generated method stubreturn Service.START_STICKY;}onStartCommand()返回值,即设定了Service的重新启动模式,eg:STAR_STICKY、STAR_NOT_STICKY、STAR_REDELIVER_INTENT等等。
上面所说的Onstat()处理程序等同于重写了OnStartCommand()并返回STAR_STICKY.
B、在OnStartComand()返回值中,指定重新启动模式,将会影响后面的调用中 传入参数的值。
eg.intent、flags、startId的值。
通过StartService()启动service代码:
Intent intent=new Intent(this,MyService.class);startService(intent);
当然也可以隐式启动。
context.bindService()启动流程:
context.bindService() -> onCreate() -> onBind() -> Service running -> onUnbind() -> onDestroy() -> Service stop通过BindService()启动Service,可以将一个activity和一个Service绑定起来,前者会维持一个对后者的实例的引用,实现对正在运行的Service进行方法调用。
代码如下:
MyService.java
private final IBinder binder=new MyBinder();public class MyBinder extends Binder{MyService getService(){return MyService.this;}}@Overridepublic IBinder onBind(Intent arg0) {return binder;}
MainActivity.java
private MyService myService;/** * 处理Service和activity之间进行连接和数据传递 */private ServiceConnection mConnection=new ServiceConnection() {@Overridepublic void onServiceConnected(ComponentName arg0, IBinder mbinderService) {//当建立连接时调用myService=((MyService.MyBinder)mbinderService).getService();}@Overridepublic void onServiceDisconnected(ComponentName arg0) {//当service意外断开时myService=null;}};启动BindService()
//绑定ServiceIntent bindIntent=new Intent(this,MyService.class);bindService(bindIntent, mConnection, flags);flags参数说明:
用来提高Service优先级,等等功能。参数有:BIND_ADJUST_WITH_ACTIVITY、BIND_IMPORTANT等等。
3、停止service
三,补充
- 浅谈Service
- 浅谈Service
- 浅谈Service
- 浅谈Service
- 浅谈web service
- Web Service 浅谈
- 浅谈Android Service 组件
- 浅谈Android Service 组件
- android service浅谈
- 浅谈android 之 service
- Web Service 浅谈
- android 浅谈service
- 浅谈Android Service 组件
- 浅谈Web Service
- 浅谈 Android Service
- 浅谈Service与Business
- 浅谈android中的Service
- Service的浅谈
- lua日期与时间操作
- 排序算法汇总总结
- mvn 下载 jar 包 源代码以及doc 文档
- WindowsPhone 支付宝网页支付
- redis安装和简单例子
- 浅谈Service
- CI学习随手记(三)
- 010 else -if 语句
- 刷算法
- UI运行环境对系统安全性的影响
- centos7简单搭建nginx+uwsgi+web.py的Python web环境(记录)
- html5 新特性支持的浏览器检测
- SQL 检测是否存在相同的行。
- vim 常用操作(更新)