Service相关--读书笔记
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相关--读书笔记的更多相关文章
- <<Java RESTful Web Service实战>> 读书笔记
<<Java RESTful Web Service实战>> 读书笔记 第一章 JAX-RS2.0入门 REST (Representational State ransf ...
- 《企业应用架构模式》(POEAA)读书笔记
原文地址:<企业应用架构模式>(POEAA)读书笔记作者:邹齐龙(技术-5013 什么是架构 Rolph Johnson认为:架构是一种主观上的东西,是专家级的项目开发人员对系统设计的一些 ...
- 【英语魔法俱乐部——读书笔记】 2 中级句型-复句&合句(Complex Sentences、Compound Sentences)
[英语魔法俱乐部——读书笔记] 2 中级句型-复句&合句(Complex Sentences.Compound Sentences):(2.1)名词从句.(2.2)副词从句.(2.3)关系从句 ...
- TJI读书笔记13-内部类
TJI读书笔记13-内部类 TJI读书笔记13-内部类 创建内部类 内部类和外部类的关系 .this和.new 内部类和向上转型 局部内部类 匿名内部类 匿名内部类的定义和初始化 使用匿名内部类来实现 ...
- 图解TCP/IP读书笔记(二)
图解TCP/IP读书笔记(二) 第二章.TCP/IP基础知识 一.TCP/IP出现的背景及其历史 年份 事件 20世纪60年代后半叶 应DoD(美国国防部)要求,美国开始进行通信技术相关的研发 196 ...
- SSL读书笔记
摘要: 第一次写博客,为读书笔记,参考书目如下: <HTTP权威指南> <图解HTTP> <大型分布式网站架构设计与实践> 作者:陈康贤 一. HTTP+SSL=H ...
- 读书笔记 之 《阿里巴巴Java开发手册》
一.前言 这本书主要定义了一些代码的规范以及一些注意事项.我只根据我自己的不足,摘录了一些内容,方便以后查阅. 二.读书笔记 命名 1.代码中的命名均不能以下划线或美元符号开始,也不能以下划线或美元符 ...
- spring揭秘 读书笔记 二 BeanFactory的对象注册与依赖绑定
本文是王福强所著<<spring揭秘>>一书的读书笔记 我们前面就说过,Spring的IoC容器时一个IoC Service Provider,而且IoC Service Pr ...
- spring揭秘 读书笔记 一 IoC初探
本文是王福强所著<<spring揭秘>>一书的读书笔记 ioc的基本概念 一个例子 我们看下面这个类,getAndPersistNews方法干了四件事 1 通过newsList ...
随机推荐
- tracert 命令详解
tracert 命令详解 How to Use the TRACERT Utility The TRACERT diagnostic utility determines the route to a ...
- Android目标大纲
为了更好的便于复习 特制作此份大纲 1 J2SE基础 集合框架源码解析2 JVM3 TCP/IP HTTP4 数据结构与算法5 Android6 项目技术点7 开源库解析8 设计模式
- STM32学习笔记(二) 基于STM32-GPIO的流水灯实现
学会了如何新建一个工程模板,下面就要开始动手实践了.像c/c++中经典的入门代码"hello world"一样,流水灯作为最简单的硬件设备在单片机领域也是入门首推.如果你已经有了一 ...
- (转)Thread.setDaemon设置说明
本想搜下python多线程里的setDaemon,发现了这篇文章写得很不错:http://blog.csdn.net/m13666368773/article/details/7245570 Thre ...
- Android LayoutInflater 动态地添加删除View
我想实现点击一个按钮(或其他的事件)添加或删除View,网上找到了LayoutInflater这个类. 下面是我自己一些经验: android官网上LayoutInflater的API:http:// ...
- final简介
final简介 final用来修饰方法和属性表示特殊的意义.修饰方法时表示方法不能被重写:修饰属性时表示属性不能被改变,这里属性又分为对象和基本类型,修饰基本类型表示基本类型赋值以后不能再被赋值,修饰 ...
- phalcon: acl权限控制
目录控制: public/index.php: $di['aclResource']=function(){ return include_once '../app/config/frontbackA ...
- C语言中的转义字符
转义字符 意义 ASCII码值(十进制) \a 响铃(BEL) 007 \b 退格(BS) ,将当前位置移到前一列 008 \f 换页(FF),将当前位置移到下页开头 012 \n 换行(LF) ,将 ...
- 连续型变量的推断性分析——t检验
连续型变量的推断性分析方法主要有t检验和方差分析两种,这两种方法可以解决一些实际的分析问题,下面我们分别来介绍一下这两种方法 一.t检验(Student's t test) t检验也称student ...
- HDUOJ----1234 开门人和关门人(浙江大学考研题)
开门人和关门人 Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Sub ...