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. STM32学习笔记(三) STM32的GPIO的深入学习

    STM32的开发学习主要涉及软硬件两个部分的实现,包含众多外设和总线的理解配置.STM32的整个学习曲线并不陡峭,但入门却相当困难,因此在学习之初,多动手实验和测试相当重要,GPIO作为整个STM32 ...

  2. Android 进入页面默认定位到ListView的解决方法

    由于ListView会默认去获取焦点,如果说ListView在页面的下方的话,那么点击条目进入新页面并退出,那么这时候就会定位到ListView这里,而不是展示头部.   解决这个问题,只需要在Lis ...

  3. 强制关闭tomcat

    ps -ef |grep tomcat //找到tomcat的端口号 kill - tomcatpid

  4. php学习记录 易混淆

    1.echo和print的区别 PHP中echo和print的功能基本相同(输出),但是两者之间还是有细微差别的.echo输出后没有返回值,但print有返回值,当其执行失败时返回flase.因此可以 ...

  5. 【图像处理Matlab】2 灰度变换 imadjust stretchlim

    f=imread('123.tif'); % 读入一幅图片 g=imadjust(f,[ ],[ ]); % 负片显示 [imadjust] imadjust(f, [low_in high_in], ...

  6. maven各种插件在总结

    http://blog.csdn.net/taiyangdao/article/category/6377863  好文章系列课程

  7. JQuery & Javascript

    Jquery 是一个优秀的javascript框架,是轻量级的js库 jQuery简化了javascript 编程 jQuery很容易学习

  8. .NET简谈反射(动态调用)

    我们继续C#基础知识的学习,这篇文章主要要讲的是我们C#程序员迈向高级C#程序员的关键性的一步. 有的朋友会说事实不是这样的,我不用反射就不能开发吗?当然可以,但是用与不用肯定是不一样的,任何复杂抽象 ...

  9. addEventListener,attachEvent

    addEventListener是js填加事件:用法如下: target.addEventListener(type,listener,useCapture) target: 文档节点.documen ...

  10. 背景大图隔几秒切换(非轮播,淡入淡出)--变形金刚joy007 项目总结

    工作日想了好久,周日回家才想出来的... 图片切换(非轮播,淡入淡出) 1.切换2.停止 <html> <head> <meta content="text/h ...