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. WDS 的两种实现方式

    转自:http://blog.chinaunix.net/uid-26527046-id-3627627.html WDS 的两种实现方式 WDS(Wireless Distribution Syst ...

  2. Poco C++——HTTP的post请求和get请求

    两种请求都需要包含头文件: #include <iostream> #include <string> #include "Poco/Net/HTTPClientSe ...

  3. Android提高篇之自定义dialog实现processDialog“正在加载”效果、使用Animation实现图片旋转

     知识点: 1.使用imageview.textview自定义dialog 2.使用Animation实现图片旋转动画效果 3.通过自定义theme去掉dialog的title 没有使用progres ...

  4. 队列 - 从零开始实现by C++

    参考链接:数据结构探险-队列篇 数据结构太重要了,不学好是没法进行软件开发的. C++写数据结构基本套路:一个.h文件写该数据结构类的接口:一个.cpp文件写接口的具体实现:一个main.cpp用于测 ...

  5. ScrollVIew 边界阴影效果

    一.删除android ScrollView边界阴影方法方法 1) 在xml中添加:android:fadingEdge=”none” 2) 代码中添加:ScrollView.setHorizonta ...

  6. VC++ 中使用 std::string 转换字符串编码

    目录 第1章说明    1 1.1 代码    1 1.2 使用    4 第1章说明 VC++中宽窄字符串的相互转换比较麻烦,借助std::string能大大减少代码量. 1.1 代码 函数声明如下 ...

  7. unity3d magnitude的意义

    http://blog.csdn.net/fzhlee/article/details/8663564   magnitude (Read Only) 返回向量的长度,也就是点P(x,y,z)到原点( ...

  8. HTML5自学笔记[ 15 ]canvas绘图实例之钟表

    <!doctype html> <html> <head> <meta charset="utf-8"> <title> ...

  9. hdu 3172 Virtual Friends (映射并查集)

    Virtual Friends Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)T ...

  10. org.springframework.web.servlet.PageNotFound No mapping found for HTTP request with URI [/AssetRepair/assetRepairController/test.do] in DispatcherServlet with name 'assetrepair'

    web.xml文件配置: xxx-servlet.xml 我们可以发现DispatcherServlet会处理"jsp"后缀的请求;而模型视图后缀也是jsp的 如果这样配置会报以下 ...