Android  Service类与生命周期

Service是Android四大组件与Activity最相似的组件,都代表可执行的程序,区别在于Service一直在后台运行且没有用户界面。

1.Service的类图和生命周期

先来看看Service的类图:

接下来看看Service的生命周期:

2.开发Service

(1)开发Service需要两步:

第1步:定义子类,继承Service

第2步:在AndroidManifest.xml文件中配置Service

(2)创建Service

public class MyService extends Service {

// 必须实现,绑定该Service时被回调

@Override

public IBinder onBind(Intent intent) {

return null;

}

// Service被创建时回调

@Override

public void onCreate() {

super.onCreate();

// 定义相关业务逻辑

System.out.println("Service is Created");

}

// Service被启动时回调

@Override

public int onStartCommand(Intent intent, int flags, int startId) {

// 定义相关业务逻辑

System.out.println("Service is Started");

return START_STICKY;

}

// Service被关闭之前回调

@Override

public void onDestroy() {

super.onDestroy();

System.out.println("Service is Destroyed");

}

}

(3)配置Service

...

接下来就可以运行Service了。

(4)启动和停止Service(一般方式)

// 创建启动Service的Intent

final Intent intent = new Intent();

// 为Intent设置Action属性

intent.setAction("com.gc.service.MY_SERVICE");

...

// 启动指定Serivce

startService(intent);

...

// 停止指定Serivce

stopService(intent);

当程序使用startService()、stopService()启动、关闭Service时,Service与访问者之间无法进行通信、数据交换,故下面介绍另一种方式启动和停止Service。

(5)启动和停止Service(绑定Service并与之通信)

如果Service和访问者之间需要进行方法调用或数据交换,则应该使用bindService()和unbindService()方法启动、停止Service。

bindService(Intent intent, ServiceConnection conn, int flags),三个参数如下:

intent:指定要启动的Service

conn:用于监听访问者与Service之间的连接情况,当访问者与Service之间连接成功时将回调该ServiceConnection对象的onServiceConnected(ComponentName name, IBinder service)方法;反之回调该ServiceConnection对象的onServiceDisconnected(ComponentName name)方法(主动调用unbindService方法断开连接时则不回调)

flags:指定绑定时是否创建Service,0:不自动创建;BIND_AUTO_CREATE:自动创建

注意:ServiceConnection对象的onServiceConnected方法中有一个IBinder对象,该对象即可实现与绑定Service之间的通信。

在绑定本地Service的情况下,onBind(Intent intent)方法所返回的IBinder对象将会传给ServiceConnection对象里onServiceConnected(ComponentName name, IBinder service)方法的service参数,这样访问者就可以通过该IBinder对象与Service进行通信。

实际开发通常会采用继承Binder(IBinder的实现类)的方式实现自己的IBinder对象。

public class MyService extends Service {

private int count;

// 定义onBinder方法所返回的对象

private MyBinder binder = new MyBinder();

// 通过继承Binder来实现IBinder类

public class MyBinder extends Binder {

public int getCount() {

return count; // 获取Service的运行状态

}

}

// 必须实现,绑定该Service时被回调

@Override

public IBinder onBind(Intent intent) {

System.out.println("Service is Binded");

return binder; // 返回IBinder对象

}

// Service被创建时回调

@Override

public void onCreate() {

super.onCreate();

System.out.println("Service is Created");

count = 100;

}

// Service被断开连接时回调

@Override

public boolean onUnbind(Intent intent) {

System.out.println("Service is Unbinded");

return true;

}

// Service被关闭之前回调

@Override

public void onDestroy() {

super.onDestroy();

System.out.println("Service is Destroyed");

}

}

接下来定义一个Activity来绑定该Service,并在该Activity中通过MyBinder对象访问Service的内部状态。

在该Activity绑定该Service后,该Activity还可以通过MyBinder对象来获取Service的运行状态。对于Service的onBind(Intent intent)方法返回的IBinder对象来说,Service允许客户端通过该IBinder对象来访问Service内部的数据,这样即可实现客户端与Service之间的通信。

public class MyServiceTest extends Activity {

// Service的IBinder对象

MyService.MyBinder binder;

// 定义一个ServiceConnection对象

private ServiceConnection conn = new ServiceConnection() {

// 当该Activity与Service连接成功时回调

@Override

public void onServiceConnected(ComponentName name, IBinder service) {

// 获取Service的onBind方法所返回的MyBinder对象

binder = (MyService.MyBinder) service;

}

// 当该Activity与Service断开连接时回调

@Override

public void onServiceDisconnected(ComponentName name) {

}

};

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

...

// 创建启动Service的Intent

final Intent intent = new Intent();

// 为Intent设置Action属性

intent.setAction("com.gc.service.MY_SERVICE");

// 绑定指定Serivce

bindService(intent, conn, Service.BIND_AUTO_CREATE);

...

binder.getCount(); // 获取Serivce的count值

...

// 解除绑定Serivce

unbindService(conn);

}

}

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

Android生命周期帮助类,Android Service类与生命周期详细介绍_Android_脚本之家相关推荐

  1. Android底层隐私数据,Android Intent传递数据底层分析详细介绍_Android_脚本之家

    Android  Intent传递数据底层分析详细介绍 我们知道在Activity切换时,如果需要向下一个ActivityB传递数据,可以借助Intent对象的putExtra方法. 但是不知各位有没 ...

  2. android webservice 传递对象,Android通过ksoap2传递复杂数据类型及CXF发布的webservice详细介绍...

    Android通过ksoap2传递复杂数据类型及CXF发布的webservice详细介绍 最近在学校搞点东西,搞了2天的webservice,心累呀,今天中午和小伙伴终于弄通了,感觉就是一些细节问题没 ...

  3. android 生命周期管理,Android Activity生命周期和堆栈管理的详解_Android_脚本之家...

    Activity的生命周期 Activity是Android中的四大组件之一,也是最基本,最重要的组件,是android系统提供一个可视化的,能与用户交换的组件. 系统提供的组件,不需要用户实例化,用 ...

  4. xml 和android脚本之家,AndroidManifest.xml配置文件解析_Android_脚本之家

    标签的语法范例. android:alwaysRetainTaskState=['true' | 'false'] android:clearTaskOnLaunch=['true' | 'false ...

  5. java代码生成springdao_请JAVA高手推荐个SSH的后台代码生成工具!!要能生成Spring整合Hibernate的DAO类和Service类!...

    我是要生成DAO层和service层的类代码!!!不是配置文件!例如importjava.util.List;importorg.apache.commons.logging.Log;importor ...

  6. android 切换 preferencefragment,Android PreferenceActivity与PreferenceFragment详解及简单实例_Android_脚本之家...

    Android  PreferenceActivity与PreferenceFragment 前言 转来转去又回到了Android,闲话少说,这里是参考Android原生的Settings应用来介绍一 ...

  7. html5跟随手指的小球,Android自定义圆形View实现小球跟随手指移动效果(详细介绍)...

    一. 需求功能 手指在屏幕上滑动,红色的小球始终跟随手指移动. 实现的思路: 1)自定义View,在onDraw中画圆作为小球: 2)重写自定义View的onTouchEvent方法,记录触屏坐标,用 ...

  8. android+定时器+动画,Android 实现定时器的四种方式总结及实现实例_Android_脚本之家...

    Android中实现定时器的四种方式 第一种方式利用Timer和TimerTask 1.继承关系 java.util.Timer 基本方法 schedule 例如: timer.schedule(ta ...

  9. android sharedpre,Android SharedPreferences四种操作模式使用详解_Android_脚本之家

    Android  SharedPreferences详解 获取SharedPreferences的两种方式: 1 调用Context对象的getSharedPreferences()方法 2 调用Ac ...

最新文章

  1. SecureCRT 端口转发连接服务器
  2. 正则表达式中空格的危害
  3. 9.12測试(四)——測试笔
  4. WEB-INF目录下登录表单提交的重定向
  5. 一文详解DeepMind最新模型SUNDAE,了解迭代去噪模型的前世今生
  6. 30kJava程序员升为全栈架构师的晋升之路
  7. 跨站脚本专题 XSS
  8. qt窗口左上角坐标变动函数使用中的误区
  9. c++软件开发面试旋极面试题_腾讯软件开发面试题(有详细解答)
  10. 【数据挖掘】通用论坛正文提取
  11. Java怎么学?分享6个学习窍门
  12. Detached InstanceError:Instance is not bound to a Session 关闭session后使用SQLAlchemy对象
  13. 三方协议,劳动合同,劳务合同的区别
  14. The error may exist in bshr/mapper/PfmMapper.xml ### The error may involve defaultParameterMap
  15. mac怎么强制退出程序,强制退出Mac程序,mac 强制退出程序
  16. ecshop mysql 30秒_ecshop数据库字段说明汇总
  17. new File()获取图片地址
  18. 一名合格的网络管理员应该具备哪些技能
  19. Jackson详细介绍
  20. JAVA组件--表格-- JIDE Grids

热门文章

  1. 给P40让路!华为Mate 30 5G降至这个价,还贵吗?
  2. 安卓双屏折叠手机!看了微软时隔四年发布的手机 手里的iPhone差点掉地上
  3. 比新iPhone好看多了!华为Mate 30系列机型外观曝光
  4. 江淮汽车涉嫌排放造假 罚款1.7亿
  5. OPPO Find X继任者来了!Find Z曝光:搭载骁龙855
  6. oSIP开发者手册 (三)
  7. python不联网安装selenium_Anaconda python 离线安装selenium3.141很容易
  8. 行政区村界线_市政府批复!崇川区部分行政区划调整
  9. yaml文件解析:golang篇
  10. ubuntu 14.04系统DHCP服务器搭建