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中if __name__ == '__main__'

    python 中__name__ = '__main__' 的作用,到底干嘛的? 有句话经典的概括了这段代码的意义: “Make a script both importable and execut ...

  2. python 在不同层级目录import 模块的方法

    有一个文件夹/home/a,  里面有个模块叫b.py,  我怎么把他import到程序里? 1). import sys; sys.path.append("/home/a/") ...

  3. 【服务器环境搭建-Centos】常用系统命令篇

    uname -a 查看系统信息

  4. OpenGL的glClearColor和glClear改变背景颜色

    OpenGL的glClearColor和glClear改变背景颜色 结合以下两个函数void glClearColor(GLclampf red,    GLclampf green, GLclamp ...

  5. RAC 移动 OCR

    1.查看是否有OCR备份 # ocrconfig -showbackup 如果没有就备份一份 # ocrconfig -export /oracle/bak/ocr/ocr_11291433_exp. ...

  6. SSH命令行上传/下载文件

    上传:scp /path/file(这部分为本地的路径) user(远端目标用户名)@host(远端目标IP):/pathorfile(文件存储路径) 下载:scp user(远端用户名)@host( ...

  7. phalcon: router规则与解析,已经生成router的链接地址

    本人采用的是假分模块(目录),通过命名空间来进行模块分组的,非官方分组,所以在router是都会加上 namespace 信息,你也可适当的参考: 前提: /** * 注册命名空间 */ $loade ...

  8. 联想G480笔记本安装系统

    联想G480笔记本安装系统 联想G480笔记本,配置i5双核四线程处理器,4G内存,500G硬盘,USB3.0接口,NVIDIA GeForce GT 610M+Intel HD Graphics 3 ...

  9. dom event无法获取问题

    下列几种情况下无法获取到event,ff浏览器没测试. 1.a标签href调用的js事件 2.调用parent中事件,即子窗口调用父窗口页面中js 3....

  10. Python第三方常用工具、库、框架等

    Python ImagingLibrary(PIL):它提供强大的图形处理的能力,并提供广泛的图形文件格式支持,该库能进行图形格式的转换.打印和显示.还能进行一些图形效果的处理,如图形的放大.缩小和旋 ...