2013-12-30 18:16:11

1. Service和Activty都是从Context里面派生出来的,因此都可以直接调用getResource(),getContentResolver()等方法。

2. 启动Service有两种方式:

2.1 startService():该方法启动Service,访问者和Service之间没有关联,一旦启动,即使访问者退出,Service依然运行;

2.2 bindService():该方法启动Service,访问者和Service绑定在一起,一旦访问者退出,Service随即退出。

3. onCreate()只会被调用一次,onStartCommand()方法每次Service被启动时都会被调用。

4. 绑定本地Service并与之通信:

4.1 当程序通过startService()、stopService()来启动、停止Service时,Service和访问者之间无法进行通信和数据交换。

4.2 如果要实现访问者和Service之间通信、交换数据,那么需要使用bindService()和unBindService()来启动、停止Service。

5. 程序实例:

先来一张图:

MyService.java

 package com.example.localservice;

 import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log; public class MyService extends Service {
private int i;
private MyBinder myBinder; // Define our own Binder class
public class MyBinder extends Binder {
// Any methods you can defined.
public int getValue() {
return i;
}
} @Override
public void onCreate() {
// Something the service doing.
super.onCreate();
myBinder = new MyBinder();
new Thread() {
public void run() {
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
i++;
}
};
}.start();
} // Return our own Binder object.
@Override
public IBinder onBind(Intent intent) {
return myBinder;
} @Override
public boolean onUnbind(Intent intent) {
Log.d("David", "intent = " + intent);
return super.onUnbind(intent);
} @Override
public void onDestroy() {
Log.d("David", "-------onDestroy!");
super.onDestroy();
} }

MainActivity.java

 package com.example.localservice;

 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.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast; import com.example.localservice.MyService.MyBinder; public class MainActivity extends Activity {
private MyBinder myBinder;
private Button btnBindService;
private Button btnUnbindService;
private Button btnGetValue; ServiceConnection connection = new ServiceConnection() { // Two call-back methods.
@Override
public void onServiceDisconnected(ComponentName name) {
Log.d("David", "ServiceDisconnected!");
} @Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.d("David", "ServiceConnected!");
myBinder = (MyBinder) service;
}
}; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnBindService = (Button) findViewById(R.id.btn_bind_service);
btnUnbindService = (Button) findViewById(R.id.btn_unbind_service);
btnUnbindService.setEnabled(false);
btnGetValue = (Button) findViewById(R.id.btn_get_value);
btnGetValue.setEnabled(false);
btnBindService.setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) {
Intent intent = new Intent("android.intent.action.DAVID");
bindService(intent, connection, BIND_AUTO_CREATE); // Bind service with connection.
Log.d("David", "Bind service!");
btnUnbindService.setEnabled(true);
btnGetValue.setEnabled(true);
}
}); btnUnbindService.setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) {
if (connection != null) {
// stopService(new Intent("android.intent.action.DAVID"));
unbindService(connection);
Log.d("David", "Unbind service!");
}
}
}); btnGetValue.setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) {
if (myBinder == null) {
Toast.makeText(MainActivity.this,
"Please bind service first!", Toast.LENGTH_LONG)
.show();
return;
}
Log.d("David", "Got value = " + myBinder.getValue());
}
});
} }

代码和操作很简单,看button title即可。源码下载

遇到一个问题:先Bind service,然后点击第三个button,发现可以取到值,此时点击第二个button,unbind service,再点击第三个button发现还是能取到值,这个还得在研究研究,当然了,有知道答案的言语一声。

6. Android的远程调用

Android的远程调用和Java的RMI类似,一样都是先定义一个远程调用接口,然后为该接口提供一个实现类即可。与RMI不同的是,客户端访问Service时,Android并不是直接返回Serivce对象给客户端,而是将一个回调对象IBinder通过onBind()方法返回给客户端。

7. 本地调用Serivce,onBind()方法返回的是IBinder对象,远程调用返回的是IBinder对象的代理。

程序实例:Server端

IServer.aidl

 package com.example.serviceserver;

 interface IServer{
String getColor();
}

ServiceServer.java

 package com.example.serviceserver;

 import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException; public class ServiceServer extends Service {
private int i;
private StringBuffer sBuffer = new StringBuffer("ServiceServer");
private MyBinder myBinder; public class MyBinder extends IServer.Stub { @Override
public String getColor() throws RemoteException {
return sBuffer.toString();
} } @Override
public void onCreate() {
super.onCreate();
myBinder = new MyBinder();
new Thread() {
public void run() {
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
sBuffer.append(i + "");
i++;
}
};
}.start();
} @Override
public IBinder onBind(Intent intent) {
return myBinder;
}
}

Client端:

IServer.aidl

 package com.example.serviceserver;

 interface IServer{
String getColor();
}

MainActivity.java

 package com.example.serviceclient;

 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.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast; import com.example.serviceserver.IServer; public class MainActivity extends Activity {
private IServer myBinder;
private Button btnBindService;
private Button btnUnbindService;
private Button btnGetValue; ServiceConnection connection = new ServiceConnection() { // Two call-back methods.
@Override
public void onServiceDisconnected(ComponentName name) {
Log.d("David", "ServiceDisconnected!");
} @Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.d("David", "ServiceConnected!");
myBinder = IServer.Stub.asInterface(service);
}
}; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnBindService = (Button) findViewById(R.id.btn_bind_service);
btnUnbindService = (Button) findViewById(R.id.btn_unbind_service);
btnUnbindService.setEnabled(false);
btnGetValue = (Button) findViewById(R.id.btn_get_value);
btnGetValue.setEnabled(false);
btnBindService.setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) {
Intent intent = new Intent("android.intent.action.main.DAVID");
bindService(intent, connection, BIND_AUTO_CREATE); // Bind
Log.d("David", "Bind service!");
btnUnbindService.setEnabled(true);
btnGetValue.setEnabled(true);
}
}); btnUnbindService.setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) {
if (connection != null) {
// stopService(new Intent("android.intent.action.DAVID"));
unbindService(connection);
Log.d("David", "Unbind service!");
}
}
}); btnGetValue.setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) {
if (myBinder == null) {
Toast.makeText(MainActivity.this,
"Please bind service first!", Toast.LENGTH_LONG)
.show();
return;
}
try {
Log.d("David", "Got value = " + myBinder.getColor());
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
} }

还是这个问题:先Bind service,然后点击第三个button,发现可以取到值,此时点击第二个button,unbind service,再点击第三个button发现还是能取到值。有知道的同学欢迎拍砖。

源码下载

先运行SeriviceServer,然后再启动ServiceClient,比较简单,留做笔记吧,希望对同学们有帮助。

Service相关--读书笔记的更多相关文章

  1. <<Java RESTful Web Service实战>> 读书笔记

    <<Java RESTful Web Service实战>> 读书笔记 第一章   JAX-RS2.0入门 REST (Representational State ransf ...

  2. 《企业应用架构模式》(POEAA)读书笔记

    原文地址:<企业应用架构模式>(POEAA)读书笔记作者:邹齐龙(技术-5013 什么是架构 Rolph Johnson认为:架构是一种主观上的东西,是专家级的项目开发人员对系统设计的一些 ...

  3. 【英语魔法俱乐部——读书笔记】 2 中级句型-复句&合句(Complex Sentences、Compound Sentences)

    [英语魔法俱乐部——读书笔记] 2 中级句型-复句&合句(Complex Sentences.Compound Sentences):(2.1)名词从句.(2.2)副词从句.(2.3)关系从句 ...

  4. TJI读书笔记13-内部类

    TJI读书笔记13-内部类 TJI读书笔记13-内部类 创建内部类 内部类和外部类的关系 .this和.new 内部类和向上转型 局部内部类 匿名内部类 匿名内部类的定义和初始化 使用匿名内部类来实现 ...

  5. 图解TCP/IP读书笔记(二)

    图解TCP/IP读书笔记(二) 第二章.TCP/IP基础知识 一.TCP/IP出现的背景及其历史 年份 事件 20世纪60年代后半叶 应DoD(美国国防部)要求,美国开始进行通信技术相关的研发 196 ...

  6. SSL读书笔记

    摘要: 第一次写博客,为读书笔记,参考书目如下: <HTTP权威指南> <图解HTTP> <大型分布式网站架构设计与实践> 作者:陈康贤 一. HTTP+SSL=H ...

  7. 读书笔记 之 《阿里巴巴Java开发手册》

    一.前言 这本书主要定义了一些代码的规范以及一些注意事项.我只根据我自己的不足,摘录了一些内容,方便以后查阅. 二.读书笔记 命名 1.代码中的命名均不能以下划线或美元符号开始,也不能以下划线或美元符 ...

  8. spring揭秘 读书笔记 二 BeanFactory的对象注册与依赖绑定

    本文是王福强所著<<spring揭秘>>一书的读书笔记 我们前面就说过,Spring的IoC容器时一个IoC Service Provider,而且IoC Service Pr ...

  9. spring揭秘 读书笔记 一 IoC初探

    本文是王福强所著<<spring揭秘>>一书的读书笔记 ioc的基本概念 一个例子 我们看下面这个类,getAndPersistNews方法干了四件事 1 通过newsList ...

随机推荐

  1. Python学习笔记--XML的应用

    XML的定义 XML 指可扩展标记语言(EXtensible Markup Language) XML 是一种标记语言,很类似 HTML XML 的设计宗旨是传输数据,而非显示数据 XML 标签没有被 ...

  2. (一)mtg3000常见操作

    一.查看MTG3000主控板IP地址: 重启设备后一直跑到shell,用户名和密码都输入admin,然后输入en进入命令行界面,输入sh int可查看设备IP等信息. 2.升级app.web程序

  3. Object Pascal 语法之异常处理

    http://www.cnblogs.com/spider518/archive/2010/12/30/1921298.html 3 结构化异常处理 结构化异常处理(SHE)是一种处理错误的手段,使得 ...

  4. STM32学习笔记(二) 基于STM32-GPIO的流水灯实现

    学会了如何新建一个工程模板,下面就要开始动手实践了.像c/c++中经典的入门代码"hello world"一样,流水灯作为最简单的硬件设备在单片机领域也是入门首推.如果你已经有了一 ...

  5. 移动端 meta

    摘自http://www.cnblogs.com/shxydx/articles/2856882.html   控制显示区域各种属性: <meta content="width=dev ...

  6. hdu4418(概率dp + 高斯消元)

    应该是一个入门级别的题目. 但是有几个坑点. 1. 只选择x能到达的点作为guass中的未知数. 2. m可能大于n,所以在构建方程组时未知数的系数不能直接等于,要+= 3.题意貌似说的有问题,D为- ...

  7. hiho_99_骑士问题

    题目大意 给定国际象棋8x8棋盘上三个起始点,三个骑士分别从三个起始点开始移动(骑士只能走日字,且骑士从任意一点出发可以走遍整个棋盘).现要求三个骑士汇聚到棋盘上某个点,且使得骑士到达该点所移动的次数 ...

  8. django在pyhton2.7 和 python3.* 之间代码和睦相处的方法

    “祥”龙第一掌: from __future__ import unicode_literals from django.utils.encoding import python_2_unicode_ ...

  9. js鼠标拖拽

    html <div id="box"> </div> css ;;} #box{width:200px;height:200px;background:cy ...

  10. Linux基础: 一切都是文件

    ​ 一切都是文件 创建系统配置交换分区(用作虚拟内存)加上单根树 file 文件名 查看文件类型 uname 查看系统版本 bin binary二进制文件 所有用户可用 系统可执行命令的二进制文件(c ...