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(){....}); 当这样会有 ...
随机推荐
- u-boot向linux内核传递启动参数(详细)
U-BOOT 在启动内核时,会向内核传递一些参数.BootLoader 可以通过两种方法传递参数给内核,一种是旧的参数结构方式(parameter_struct),主要是 2.6 之前的内核使用的方式 ...
- Swift不可变数组
Objective-C编写了2个不同的类来区分不可变数组(NSArray)和可变数组(NSMutableArray): Swift通过使用常量和变量来区分不可变数组和可变数组. 只要将数组定义为常量, ...
- [GRYZ2015]阿Q的停车场
题目描述 刚拿到驾照的KJ 总喜欢开着车到处兜风,玩完了再把车停到阿Q的停车场里,虽然她对自己停车的水平很有信心,但她还是不放心其他人的停车水平,尤其是Kelukin.于是,她每次都把自己的爱车停在距 ...
- MFC程序运行流程
->进入入口函数_tWinMain() 程序首先进入文件AppModul.cpp,找到_tWinMain()函数运行,调用其中的AfxWinMain()函数. 由于为了支持UNICODE,C运行 ...
- 洛谷 P1273 有线电视网
2016-05-31 13:25:45 题目链接: 洛谷 P1273 有线电视网 题目大意: 在一棵给定的带权树上取尽量多的叶子节点,使得sigma(val[选择的叶子节点])-sigma(cost[ ...
- -lrt
在编写pthread有关的程序时,编译时老是报"undefined reference to `pthread_create'"的错误,原因是没有链接pthread相关的库,gcc ...
- CDH ecosystem components
1,Mahout ASF(Apache Software Foundation)开源项目,提供可扩展的`机器学习`--(ML,Machine Learning多领域交叉学科,涉及概率,统计,逼近,凸分 ...
- 2016多校第六场题解(hdu5793&hdu5794&hdu5795&hdu5800&hdu5802)
这场就做出一道题,怎么会有窝这么辣鸡的人呢? 1001 A Boring Question(hdu 5793) 很复杂的公式,打表找的规律,最后是m^0+m^1+...+m^n,题解直接是(m^(n+ ...
- hdoj 2037 今年暑假不AC
今年暑假不AC Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Sub ...
- JPA主键策略
JPA 自带的主键策略有 4 种,在枚举 javax.persistence.GenerationType 中,分别是:TABLE.SEQUENCE.IDENTITY.AUTO. TABLE:通过表产 ...