android 四大组件之Service两种调用方式使用详解
来源:互联网 发布:淘宝网第三方支付平台 编辑:程序博客网 时间:2024/05/01 09:56
一 概述
Service服务作为android中的四大组件之一,其作用和重要性也不用多说。service用于长期在后台处理任务,与Activity相反Service没有可见的用户界面,但Service能长时间在后台运行,Service是一个具有较长生命周期但没有用户界面的组件,和Activity一样的是Service也有自己的生命周期。下图是它的生命周期的过程。
service有2种基本的启动方式:
startService():使用这种方式,来进行单一的任务,不需要返回结果给调用者
bindService():使用这种方式,能和调用者进行绑定,是两者有关联。
二 Service的创建,并在AndroidManifest文件中进行配置。
创建自己的Service需继承android提供的Service类,并更具功能实现其中的方法。查看Service类中的方法。
下面对几个重要的方法进行讲解:
onCreate();当服务被创建时调用,只调用一次。
onStartCommand();它与startService()对应,当服务启动后调用。如果你重写了该方法,你就有责任自己去
当任务结束以后,调用stopSelf()或者stopService()来停止服务。如果你是绑定的服务,就不需重写该方法了。
onBind();它与bindService()对应,通过返回IBinder,来与service交流。如果你并不像绑定它,就直接返回null
onDestroy();当服务不再被使用时需要销毁时调用,你应该在这里用来停止线程,注销监听器,广播。
如果一个组件如activity使用的是 startService()来启动服务的话,就会触发 onStartCommand(),然后服务就会一直运行,直到任务结束;服务的停止需要
手动控制:在启动服务的组件中调用 stopService()或者在服务本类中调用stopSelf()
如果一个组件使用的是bindService()来启动服务的话,该服务就会运行,直到组件不约束它。
三 代码示例
1. 创建自己的Service,并重写onStartCommand(对应startService启动方式)和onBind(对应bindService启动方式),实现每个一秒钟打印一些内容的功能。
package com.example.servicedemo;import android.app.Service;import android.content.Intent;import android.os.Binder;import android.os.IBinder;import android.util.Log;/** * @author ZMC *创建自定义的service */public class FirstService extends Service {private MyBinder myBinder = new MyBinder();//创建一个Binder类class MyBinder extends Binder{public void startJob(){new Thread(){public void run() {for (int i = 0; i < 51; i++) {System.out.println("startJob");try {sleep(1000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}};}.start();}}//该方法给调用者返回一个IBinder对象,是和调用者经行数据交换的关键//该方法和bindService对应@Overridepublic IBinder onBind(Intent intent) {Log.i("test", "onBind");return myBinder;}@Overridepublic void onCreate() {System.out.println("Oncreate");super.onCreate();}private boolean flag = true;private int count = 1;//该方法是和startService对应的@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {// TODO Auto-generated method stubnew Thread() {@Overridepublic void run() {while (flag) {System.out.println("count:" + count);count++;try {sleep(1000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}if (count > 100) {flag = false;}}}}.start();Log.i("test","onStartCommand");return super.onStartCommand(intent, flags, startId);}//销毁方法@Overridepublic void onDestroy() {// TODO Auto-generated method stubSystem.out.println("ondestory");super.onDestroy();}}说明:
onStartCommand方法是对应startService启动方式的方法,使用startService方式启动只需要将要实现的功能写在onStartCommand即可。
onBind方法,该方法给调用者返回一个IBinder对象,是和调用者经行数据交换的关键,该方法和bindService对应,其中IBinder对象一般是自己集成Binder类实现的,上面例子中是MyBinder,其中定义了实现功能的方法,这样在当调用者得到该对象时,就能通过该对象中的方法实现相对应的功能了。
2. 布局文件
定义了四个按钮
通过四个按钮实现启动服务,暂停服务。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.servicedemo.MainActivity" > <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="start" android:text="启动服务"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="stop" android:text="停用服务"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="bind" android:text="绑定Activity"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="unbind" android:text="解绑Activity"/> </LinearLayout>3. 创建调用者
这里我用了Activity作为服务的调用者,并通过一个ServiceConnection接口的实现类来实现和Service的绑定。
package com.example.servicedemo;import com.example.servicedemo.FirstService.MyBinder;import android.app.Activity;import android.content.ComponentName;import android.content.Intent;import android.content.ServiceConnection;import android.os.Bundle;import android.os.IBinder;import android.view.View;public class MainActivity extends Activity {private Intent intent = null;private MyBinder myBinder;ServiceConnection serviceConnection = new ServiceConnection() {@Overridepublic void onServiceDisconnected(ComponentName name) {}@Overridepublic void onServiceConnected(ComponentName name, IBinder service) {myBinder = (MyBinder)service;myBinder.startJob();}};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);}public void start(View view){/* * 这样开启的服务是不受activity生命周期的影响的 * 没有办法和其他的组件进行数据交互 它是一个单独的个体 * */intent = new Intent(this,FirstService.class);startService(intent);}public void stop(View view){if (intent!=null) {stopService(intent);}}public void bind(View view){intent = new Intent(this,FirstService.class);bindService(intent, serviceConnection, BIND_AUTO_CREATE);}public void unbind(View view){unbindService(serviceConnection);}}说明:
start和stop对应的是启动服务和停用服务两个按钮的事件,同时对应为startService的启动方式。
bind和unbind对应的是绑定Activity和解绑Activity两个按钮的事件,对应bindService方式启动的。
重点:ServiceConnection该接口是一个调用者和Service关联的接口,通过该接口的实现类即可实现两者的交互。上面的代码示例中通过匿名内部类来实现的,其中实现onServiceConnected方法,该方法就是用来接收Service中onBind返回的IBinder对象的。
四 结果:
点击启动服务按钮调用onCreate和onStartCommand方法
点击停用服务调用调用ondestory方法
点击绑定按钮调用onCreate和onBind方法
点击解绑按钮调用ondestory方法
- android 四大组件之Service两种调用方式使用详解
- Android四大组件之Service的两种使用情况
- Android四大组件Service之两种的多线程启动方式
- Android四大核心组件之Service|AIDL使用详解
- Android四大组件之---Service(服务)详解
- Android 四大组件之Service详解
- Android四大组件之Service详解
- Android中的四大组件之Service详解
- android四大组件之Service详解
- Android四大组件之Service详解
- Android四大组件之Service详解
- Android四大组件之Service详解
- Android -- 四大组件之Service详解
- Android四大组件之广播注册的两种方式
- Android四大组件之Service的使用
- Android四大组件之Service详解(二)——Service在音乐播放器中的使用
- Android四大组件--Service详解
- Android组件之Service学习(1)两种使用方式与生命周期
- Swift 菜单栏
- IntelliJ IDEA 无法正常使用SVN的问题和解决办法
- poj 1743 Musical Theme(后缀自动机)
- kafka集群部署与配置手册
- Linux_7th_第1个linux驱动___给驱动模块上户口(二)
- android 四大组件之Service两种调用方式使用详解
- Java 异常处理的误区和经验总结
- 动力节点——构造方法(九)
- 为什么实体类要实现序列化?
- fragment 静态用法 InflateException 的解决方案
- OpenDialog/SaveDialog 中 Filter用法
- 解决shell命令行只显示-bash-4.1#不显示用户和路径方法
- MATLAB robot toolbox 机械臂轨迹规划
- [代码笔记] python之 类和对象(Just syntax)