Service的启动与停止、绑定与解绑
---恢复内容开始---
Service的意义就在于当软件停止之后还可以在背景中进行运行,换句话也就是说,比如一个音乐播放器,当我们退出音乐播放器的时候,还是希望它在背景中运行,也就是一直播放着音乐,这时候Service就派上了大的用途。
Service的生命周期和Activity的生命周期差不多。也有开启和停止。onCreate()方法是初始化配置,onDestroy()是释放所有剩余的资源。Service周期是发生在onCreate()和onDestroy()之间的。
startService()方法是启动Service。
StopService()方法是停止Service。
bindService()方法是启动Service的激活生命周期始于onBind()调用,在onUnbind()返回时结束。
当一个组件启动Service时,是通过startService()进行启动Service,当Service被启动之后,onStartCommand()方法被调用,并且接收startService()方法中传递的Intent值。
onStartServiceCommand()方法必修返回一个整形值。这个整形值是说明了Service在系统中如何执行。其中三个比较常用的解释如下:
START_NOT_STICKY:如果系统在onStartServiceCommand()返回后杀死Service,那么不会重新创建Service,除非有等待的Intent要传递。
START_STICKY 如果系统在onStartServiceCommand()返回后杀死Service,重启Service,并且重新调用onStartServiceCommand(),但不重新传递最新的Intent。
START_REDELIVER_INTENT 如果系统在onStartServiceCommand()返回后杀死Service,那么重新创建Service,并且最近传给Service的Intent调用onStartServiceCommand()。
创建一个Service启动周期的实例
public class MyService extends Service{
//必须实现的方法,作用是用来返回binder对象
//重写onBind()方法,返回Service实例,使Service支持绑定,实现onBind()方法,并且返回MyService实例
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
System.out.println("--onBind--");
return null;
}
//用于创建Service的方法,只能调用一次
public void onCreate(){
super.onCreate();
System.out.println("--onCreate--");
//每次启动Service时都会调用这个方法
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
System.out.println("--onStartCommand--");
return super.onStartCommand(intent, flags, startId);
}
//解绑的时候使用的这个方法
@Override
public boolean onUnbind(Intent intent) {
// TODO Auto-generated method stub
System.out.println("--onUnbind--");
return super.onUnbind(intent);
}
//退出或者销毁的时候使用这个方法
@Override
public void onDestroy() {
// TODO Auto-generated method stub
serviceRunning = false;
System.out.println("--onDestroy--");
super.onDestroy();
}
}
注意:在测试的时候一定要在onCreate()方法中写一个多线程,以便输出,让我们更加的明白。如下:
//用于创建Service的方法,只能调用一次
public void onCreate(){
super.onCreate();
System.out.println("--onCreate--");
serviceRunning = true;
new Thread(){
public void run(){
while(serviceRunning){
System.out.println("--Service运行中--");
try{
sleep(1000);
}catch(Exception e){
e.printStackTrace();
}
}
}
}.start();
}
绑定Service
绑定Service的时候会比较的复杂,其中,看绑定方法bindService(Intent service, ServiceConnection conn, int flags)时大家就可以看出。其中Intent需要传递Intent的值,conn是ServiceConnection的实例,flags是所需要的一个标示。下面就为大家解析绑定Service所需要的三个步骤:
第一步:需要在Service中创建一个Binder接口,并且实现:
包含客户端可以调用public方法
或返回当前Service的实例--也包含客户端可以调用的Public方法
或返回Service持有的其他类型的实例--也包含客户端可以调用的Public方法
代码如下:
public class MyBinder extends Binder{
MyService getService(){
return MyService.this;
}
}
第二步:在onBind()中返回Binder实例。
代码如下:
//必须实现的方法,作用是用来返回binder对象
//重写onBind()方法,返回Service实例,使Service支持绑定,实现onBind()方法,并且返回MyService实例
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
System.out.println("--onBind--");
return null;
}
第三步:在客户端中,从onServiceConnected()回调方法中接收这个Binder,并且使用Binder包含的Service提供的方法。
比如:
public class MyServiceConn implements ServiceConnection{
MyService.MyBinder binder = null;
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
binder = (MyService.MyBinder)service;
}
@Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
binder = null;
}
}
注意:一定要在客户端中声明这个实例:
final MyServiceConn myserviceconn = new MyServiceConn();
客户端在合适的时候也可以进行解绑:
//解除绑定的Service
unbind.setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) {
// TODO Auto-generated method stub
unbindService(myserviceconn);
}
});
上述就把Service的启动、停止、绑定、解绑就完成了,下面的则是客户端的一些的代码:
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button; public class MainActivity extends Activity { private Button start;
private Button stop;
private Button bind;
private Button unbind;
private Intent intent; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start = (Button)findViewById(R.id.btn1);
stop = (Button)findViewById(R.id.btn2);
bind = (Button)findViewById(R.id.btn3);
unbind = (Button)findViewById(R.id.btn4); final MyServiceConn myserviceconn = new MyServiceConn(); //给按钮设置事件,以便监听Service中的变化
//开启service
start.setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) {
// TODO Auto-generated method stub
intent = new Intent(getApplicationContext(),MyService.class);
startService(intent);
}
}); //结束Service
stop.setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) {
// TODO Auto-generated method stub
stopService(intent);
}
}); //绑定service服务
bind.setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) {
// TODO Auto-generated method stub
bindService(intent,myserviceconn,Context.BIND_AUTO_CREATE);
}
}); //解除绑定的Service
unbind.setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) {
// TODO Auto-generated method stub
unbindService(myserviceconn);
}
});
} }
XML文件的代码(只是一些简单的按钮,就不解释了):
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" > <TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/service" /> <Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="StartService" /> <Button
android:id="@+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="StopService" /> <Button
android:id="@+id/btn3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="bindService" /> <Button
android:id="@+id/btn4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="unBindService" /> </LinearLayout>
一定要注意在AndroidManifest.xml文件中加上权限:
<service android:name="com.example.servicetest.MyService">
</service>
到这里就完了,有什么不懂或者不对的地方可以留言,至于截图,上述的代码比较详细,我这里就不贴出了。
---恢复内容结束---
Service的启动与停止、绑定与解绑的更多相关文章
- 兼容8事件绑定与解绑addEventListener、removeEventListener和ie的attachEvent、detachEvent
兼容8事件绑定与解绑addEventListener.removeEventListener和ie的attachEvent.detachEvent ;(function(){ // 事件绑定 bi ...
- jQuery事件绑定、解绑、命名空间
jQuery事件绑定.解绑.命名空间 <%@ page language="java" import="java.util.*" pageEncoding ...
- React事件绑定与解绑
React中事件分类 React中事件绑定分为两种: 1.直接添加在React元素上的事件,这是React在基于Virtual DOM的基础上实现的符合w3c规范的合成事件(SyntheticEven ...
- CentOS启动和停止服务详解
服务简介Linux 系统服务是在Linux启 动时自动加载,并在Linux退出时自动停止的系统任务.在Linux 启动过程中,我们可以看得很多“starting … ”提示信息,该信息表示正在启动系统 ...
- Android四大组件之Service --- 如何启动和停止Service?
启动和停止方法主要是通过Intent来实现 以上一篇中的ServiceTest项目为例来启动和停止MyService这个服务 首先修改activity_main.xml中的代码,如下所示:<Li ...
- jQuery 学习笔记(5)(事件绑定与解绑、事件冒泡与事件默认行为、事件的自动触发、自定义事件、事件命名空间、事件委托、移入移出事件)
1.事件绑定: .eventName(fn) //编码效率略高,但部分事件jQuery没有实现 .on(eventName, fn) //编码效率略低,所有事件均可以添加 注意点:可以同时添加多个相同 ...
- jQuery之_事件绑定与解绑
使用jQuery实现事件的绑定和解绑 就是所谓的事件操作. 1. 事件绑定(2种): * eventName(function(){}) 绑定对应事件名的监听, 例如:$('#div').click( ...
- jquery中的DOM事件绑定与解绑
在jquery事件中有时候有的事件只需要在绑定后有效触发一次,当通过e.target判断触发条件有效触发后解除绑定事件,来避免多次无效触发和与未知情况造成冲突. 这时候就要用到了jquery中的事件绑 ...
- jquery中事件重复绑定以及解绑问题
一般的情况下,对于这种情况,我们常规的思路是,先解绑,再绑定,如下: $(selector).unbind('click').bind('click',function(){....}); 当这样会有 ...
随机推荐
- Android Activity四种加载方式
Android之四种加载方式 (http://marshal.easymorse.com/archives/2950 图片) 在多Activity开发中,有可能是自己应用之间的Activity跳转,或 ...
- andorid 进度条
SeekBar类似于ProgressBar,但是ProgressBar的主要功能是让用户知道目前的状态,而SeekBar的功能在于让用户调整进度,举个例子,在音乐播放器中,可以通过调整SeekBar来 ...
- 奇异秀App:奇异秀秀奇异,用大头视频来拜年
奇异秀APP是一款最新神奇的娱乐视频制作的手机应用软件,含有换头视频和特效视频两大特色功能,制作简单,效果酷炫,一键生成: 换头视频中可以由用户上传个人头像制作各种搞笑好玩的大头视频,有神曲.搞笑.节 ...
- [LeetCode]Evaluate Reverse Polish Notation(逆波兰式的计算)
原题链接:http://oj.leetcode.com/problems/evaluate-reverse-polish-notation/ 题目描述: Evaluate the value of a ...
- 微信浏览器内置JavaScript 对象:WeixinJSBridge
微信公众平台开发 微信公众平台开发模式 企业微信公众平台 微信浏览器 分享到朋友圈 发送给好友 分享到腾讯微博 作者:方倍工作室 原文: http://www.cnblogs.com/txw1958/ ...
- position属性
所有主流浏览器支持position属性: 任何版本的ie浏览器都不支持属性值“inherit”. position属性规定元素的定位类型,任何元素都可以定位,不过绝对定位或固定元素会生成一个块级框,不 ...
- PHP与MySQL动态网站开发2
处理HTML表单 <input type="text" name="city"/> 通过$_REQUEST['city'];访问,$_REQUEST ...
- Navicat通过云主机内网连接阿里云RDS
背景 公司为了安全起见,RDS设置只允许阿里云主机的内网端可以访问.这就意味,如果要操作RDS就需要连接到云主机上之后通过mysql shell操作.操作起来很复杂麻烦,今天看同事用Navicat f ...
- Solution for latex error:”Unknown graphics extension: .eps“ or "Can not find XXX"
Sample code: \begin{figure*} \centering % Requires \usepackage{graphicx} \includegraphics[width=7in] ...
- Spring配置文件的加载,及装载多个beans.xml文件
applicationContext.xml 是spring的全局配置文件,用来控制srping的特性 1 手动加载自定义的beans.xml文件 @Test public void testAut ...