bindService获得Service的binder对象对服务进行操作

Binder通信过程类似于TCP/IP服务连接过程binder四大架构Server(服务器),Client(客户端),ServiceManager(DNS)以及Binder驱动(路由器)

其中Server,Client,ServiceManager运行于用户空间,驱动运行于内核空间。这四个角色的关系和互联网类似:Server是服务器,Client是客户终端,SMgr是域名服务器(DNS),驱动是路由器。

book.java

package com.example.android_binder_testservice;

import android.os.Parcel;
import android.os.Parcelable; public class Book implements Parcelable {
private String bookName;
private String author;
private int publishDate; public Book() { } public Book(String bookName, String author, int publishDate) {
super();
this.bookName = bookName;
this.author = author;
this.publishDate = publishDate;
} public String getBookName() {
return bookName;
} public void setBookName(String bookName) {
this.bookName = bookName;
} public String getAuthor() {
return author;
} public void setAuthor(String author) {
this.author = author;
} public int getPublishDate() {
return publishDate;
} public void setPublishDate(int publishDate) {
this.publishDate = publishDate;
} @Override
public int describeContents() {
return 0;
} @Override
public void writeToParcel(Parcel out, int flags) {
out.writeString(bookName);
out.writeString(author);
out.writeInt(publishDate); } public static final Parcelable.Creator<Book> CREATOR = new Creator<Book>() {
@Override
public Book[] newArray(int size) {
return new Book[size];
} @Override
public Book createFromParcel(android.os.Parcel source) {
return new Book(source);
}
}; public Book(Parcel in) {
bookName = in.readString();
author = in.readString();
publishDate = in.readInt();
}
}

上面是一个 实现了parcelable的实体类,就是将book序列化,在putExtra到Service时会被写入内存加快程序速度

mainActivity.java

package com.example.android_binder_testservice;

import android.os.Bundle;
import android.util.Log;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button; public class MainActivity extends Activity {
Button startServiceButton;// 启动服务按钮
Button shutDownServiceButton;// 关闭服务按钮
Button startBindServiceButton;// 启动绑定服务按钮
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWidget();
regiestListener();
}
public void getWidget(){
startServiceButton = (Button) findViewById(R.id.startService);
startBindServiceButton = (Button) findViewById(R.id.bindService);
shutDownServiceButton = (Button) findViewById(R.id.stopService);
}
public void regiestListener() {
startServiceButton.setOnClickListener(startService);
shutDownServiceButton.setOnClickListener(shutdownService);
startBindServiceButton.setOnClickListener(startBinderService);
}
/** 启动服务的事件监听 */
public Button.OnClickListener startService = new Button.OnClickListener() {
public void onClick(View view) {
/** 单击按钮时启动服务 */
Intent intent = new Intent(MainActivity.this,
CountService.class);
startService(intent); Log.v("MainStadyServics", "start Service");
}
};
/** 关闭服务 */
public Button.OnClickListener shutdownService = new Button.OnClickListener() {
public void onClick(View view) {
/** 单击按钮时启动服务 */
Intent intent = new Intent(MainActivity.this,
CountService.class);
/** 退出Activity是,停止服务 */
stopService(intent);
Log.v("MainStadyServics", "shutDown serveice");
}
};
/** 打开绑定服务的Activity */
public Button.OnClickListener startBinderService = new Button.OnClickListener() {
public void onClick(View view) {
/** 单击按钮时启动服务 */
Intent intent = new Intent(MainActivity.this, UseBrider.class);
startActivity(intent);
Log.v("MainStadyServics", "start Binder Service");
}
}; }

mainActivity中当使用startService()启动Service时会调用Service的onStartCommand()

当使用bindService()则会调用onBind()方法,可能会觉了看的又看怎么没看到bindService()这个方法呢

重点在

Intent intent = new Intent(MainActivity.this, UseBrider.class);
startActivity(intent);

继续上代码

UseBrider.java

 /** 通过bindService和unBindSerivce的方式启动和结束服务 */
public class UseBrider extends FragmentActivity {
/** 参数设置 */
CountService countService; @Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new UseBriderFace(this)); Intent intent = new Intent(UseBrider.this, CountService.class);
intent.putExtra("book", new Book("name", "an", 1999));     /** 进入Activity开始服务      * conn
     */
bindService(intent, conn, Context.BIND_AUTO_CREATE); } private ServiceConnection conn = new ServiceConnection() {
/*
* 这个方法会获取到CountService的onBind方法中返回的Binder对象
* 然后就可以对服务进行某种操作了
*/
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
countService = ((CountService.ServiceBinder) service).getService();
countService.callBack();
} /** 无法获取到服务对象时的操作 */
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
countService = null;
} }; protected void onDestroy() {
super.onDestroy();
this.unbindService(conn);
Log.v("MainStadyServics", "out");
}
}

UseBriderFace.java

 public class UseBriderFace extends View{
/**创建参数*/
public UseBriderFace(Context context){
super(context);
}
public void onDraw(Canvas canvas){
canvas.drawColor(Color.WHITE);//画白色背景
/**绘制文字*/
Paint textPaint = new Paint();
textPaint.setColor(Color.RED);
textPaint.setTextSize(30);
canvas.drawText("使用绑定服务", 10, 30, textPaint);
textPaint.setColor(Color.GREEN);
textPaint.setTextSize(18);
canvas.drawText("使用绑定服务后,这个Activity关闭后", 20, 60, textPaint);
canvas.drawText("绑定的服务也会关闭", 5, 80, textPaint); }
}

UseBriderFace.java类其实就是用java定义的布局可以用xml文件代替

countService.java

 package com.example.android_binder_testservice;

 /**引入包*/
import android.app.Service;// 服务的类
import android.os.IBinder;
import android.os.Parcel;
import android.os.RemoteException;
import android.os.Binder;
import android.content.Intent;
import android.util.Log; /** 计数的服务 */
public class CountService extends Service {
private String TAG = CountService.class.getSimpleName();
/** 创建参数 */
boolean threadDisable;
int count;
Book book;
/*
* 当通过bindService()启动CountService时会调用这个方法并返回一个ServiceBinder对象
* 这个Binder对象封装着一个CountService实例,
* 客户端就可以通过ServiceBinder对服务端进行一些操作
*/
public IBinder onBind(Intent intent) {
Log.i(TAG, "onBind");
book = intent.getParcelableExtra("book");
return new ServiceBinder();
} @Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "onStartCommand");
return super.onStartCommand(intent, flags, startId);
} @Override
public boolean onUnbind(Intent intent) {
Log.i(TAG, "onUnbind");
return super.onUnbind(intent);
} @Override
public void onRebind(Intent intent) {
Log.i(TAG, "onRebind");
super.onRebind(intent);
} public void onCreate() {
super.onCreate();
/** 创建一个线程,每秒计数器加一,并在控制台进行Log输出 */
new Thread(new Runnable() {
public void run() {
while (!threadDisable) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) { }
count++;
Log.v("CountService", "Count is" + count);
}
}
}).start();
Log.i(TAG, "onCreate");
} public void onDestroy() {
super.onDestroy();
/** 服务停止时,终止计数进程 */
this.threadDisable = true;
Log.i(TAG, "onDestroy");
} public int getConunt() {
return count;
}
public void callBack(){
Log.i(TAG, "hello,i am a method of CountService");
} class ServiceBinder extends Binder {
public CountService getService() { return CountService.this;
} }
}

代码解释有了,想不出来了

源码下载地址:http://git.oschina.net/zwh_9527/Binder

android学习-IPC机制之ACtivity绑定Service通信的更多相关文章

  1. [置顶] 深入理解android之IPC机制与Binder框架

    [android之IPC机制与Binder框架] [Binder框架.Parcel.Proxy-Stub以及AIDL] Abstract [每个平台都会有自己一套跨进程的IPC机制,让不同进程里的两个 ...

  2. 二、Android学习第二天——初识Activity(转)

    (转自:http://wenku.baidu.com/view/af39b3164431b90d6c85c72f.html) 一. Android学习第二天——初识Activity 昨天程序搭建成功以 ...

  3. Android四大组件应用系列——Activity与Service交互实现APK下载

    Servic与Activity相比它没有界面,主要是在后台执行一些任务,Service有两种启动方法startService()和bindService(),startService方式Service ...

  4. 三、Android学习第三天——Activity的布局初步介绍(转)

    (转自:http://wenku.baidu.com/view/af39b3164431b90d6c85c72f.html) 三.Android学习第三天——Activity的布局初步介绍 今天总结下 ...

  5. Activity与Service通信(不同进程之间)

    使用Messenger 上面的方法只能在同一个进程里才能用,如果要与另外一个进程的Service进行通信,则可以用Messenger. 其实实现IPC(Inter-Process Communicat ...

  6. Activity与Service通信的方式有三种:

    在博客园看到的,看着挺不错的,借来分享下 继承Binder类 这个方式仅仅有当你的Acitivity和Service处于同一个Application和进程时,才干够用,比方你后台有一个播放背景音乐的S ...

  7. Activity与Service通信

    Activity与Service通信的方式有三种: 继承Binder类 这个方式只有当你的Acitivity和Service处于同一个Application和进程时,才可以用,比如你后台有一个播放背景 ...

  8. Android学习笔记(八)深入分析Service启动、绑定过程

    Service是Android中一个重要的组件,它没有用户界面,可以运行在后太做一些耗时操作.Service可以被其他组件启动,甚至当用户切换到其他应用时,它仍然可以在后台保存运行.Service 是 ...

  9. android Activity绑定Service

    activity可以绑定Service,并且可以调用Service中定义的方法 Service代码:在里面多了一个IBinder;个人理解是用来与Activity绑定的主要通道: public cla ...

随机推荐

  1. nodejs async

    官网:https://github.com/caolan/async 流程控制:简化十种常见流程的处理集合处理:如何使用异步操作处理集合中的数据工具类:几个常用的工具类 流程控制 详细说明:http: ...

  2. [ajax] quick double or multiple click ajax submit cause chrome explorer's error snatshot

    快速点击ajax提交,引发的错误截图1: snapshot -2:

  3. SQL 数据库开发一些精典的代码(转自 咏南工作室)

    1.按姓氏笔画排序: Select * From TableName Order By CustomerName Collate Chinese_PRC_Stroke_ci_as 2.数据库加密: s ...

  4. eclipse/myeclipse清除workspace

    打开Eclipse后,选择功能菜单里的 Windows -> Preferences->, 弹出对话框后,选择 General -> Startup and Shutdownwor ...

  5. H2Database聚合函数

    聚合函数(Aggregate Functions) AVG  BOOL_AND  BOOL_OR  COUNT  GROUP_CONCAT MAX  MIN  SUM  SELECTIVITY  ST ...

  6. 在Windows 7上安装Team Foundation Server(TFS)的代理服务器(Agent)

    自2009年微软发布Windows 7以来,经过8年的市场验证,Windows 7已经成为史上应用最为广泛的操作系统.但是面对技术变化的日新月异,2015年微软正式停止了对Windows 7的主流支持 ...

  7. asp.net缓存使用介绍

    介绍: 在我解释cache管理机制时,首先让我阐明下一个观念:IE下面的数据管理.每个人都会用不同的方法去解决如何在IE在管理数据.有的会提到用状态管理,有的提到的cache管理,这里我比较喜欢cac ...

  8. 如何使用linq读取DataTable集合?AsQueryable() 和 AsEnumerable()区别?

    一.准备工作 引入linq和data 相关的using命名空间 DataTable dt=new DataTable();//dt的来源可以是多个地方,比如:数据库,Excel等等.我这里使用Exce ...

  9. Jmeter——参数化的9种方法

    本文由作者张迎贞授权网易云社区发布. 一.用户定义的变量 1.右键快捷菜单中选择 添加-配置元件-用户自定义变量. 用户自定义变量中的定义的所有参数的值在测试计划的执行过程中不能发生取值的改变,因此一 ...

  10. Flask 视图,模板,蓝图.

    https://www.cnblogs.com/wupeiqi/articles/7552008.html 1. 配置文件 from flask import Flask app =Flask(__n ...