首先,大概来总结一下与Service的通信方式有很多种:

  1. 通过BroadCastReceiver:这种方式是最简单的,只能用来交换简单的数据;
  2. 通过Messager:这种方式是通过一个传递一个Messager给对方,通过这个它来发送Message对象。这种方式只能单向传递数据。可以是ServiceActivity,也可以是从Activity发送数据给Service。一个Messeger不能同时双向发送;
  3. 通过Binder来实现远程调用(IPC):这种方式是Android的最大特色之一,让你调用远程Service的接口,就像调用本地对象一样,实现非常灵活,写起来也相对复杂。

本文最重点谈一下怎么使用AIDL实现Service端和Client端的双向通信(或者叫"调用")。

首先定义一个AIDL接口如下:

// IRemoteService.aidl
package com.race604.servicelib; interface IRemoteService {
int someOperate(int a, int b);
}

这里只定义了一个简单的接口someOperate(),输入参数ab,返回一个int值。

Service的实现如下:

// RemoteService.java
package com.race604.remoteservice; import ... public class RemoteService extends Service {
private static final String TAG = RemoteService.class.getSimpleName();
private final IRemoteService.Stub mBinder = new IRemoteService.Stub() {
@Override
public int someOperate(int a, int b) throws RemoteException {
Log.d(TAG, "called RemoteService someOperate()");
return a + b;
}
}; @Override
public IBinder onBind(Intent intent) {
return mBinder; // 注意这里返回binder
}
}

这里,在RemoteService里面实现一个IRemoteService.Stub接口的Binder,并且在onBind()中返回此Binder对象。 在AndroidManifest.xmlRemoteService的申明如下:

<service
android:name=".RemoteService"
android:enabled="true"
android:exported="true" > <intent-filter>
<action android:name="com.race604.servicelib.IRemoteService" />
</intent-filter>
</service>

这里android:exported="true"表示可以让其他进程绑定,这里还有一个<action android:name="com.race604.servicelib.IRemoteService" />,这里是为了让后面的Client通过此Action来绑定。

Client的调用方法如下:

package com.race604.client;

import ...

public class MainActivity extends ActionBarActivity implements View.OnClickListener {

    private static final String TAG = MainActivity.class.getSimpleName();
private IRemoteService mService; private ServiceConnection mServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Toast.makeText(MainActivity.this, "Service connected", Toast.LENGTH_SHORT).show();
mService = IRemoteService.Stub.asInterface(service);
} @Override
public void onServiceDisconnected(ComponentName name) {
Toast.makeText(MainActivity.this, "Service disconnected", Toast.LENGTH_SHORT).show();
mService = null;
}
}; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); findViewById(R.id.bind).setOnClickListener(this);
findViewById(R.id.unbind).setOnClickListener(this);
findViewById(R.id.call).setOnClickListener(this);
} private void callRemote() { if (mService != null) {
try {
int result = mService.someOperate(1, 2);
Toast.makeText(this, "Remote call return: " + result, Toast.LENGTH_SHORT).show();
} catch (RemoteException e) {
e.printStackTrace();
Toast.makeText(this, "Remote call error!", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "Service is not available yet!", Toast.LENGTH_SHORT).show();
}
} @Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bind:
Intent intent = new Intent(IRemoteService.class.getName());
bindService(intent, mServiceConnection, BIND_AUTO_CREATE);
break;
case R.id.unbind:
unbindService(mServiceConnection);
break;
case R.id.call:
callRemote();
break;
}
}
}

在客户端,使用Context.bindService()函数,绑定到远程的Service。注意到这里的Intent intent = new Intent(IRemoteService.class.getName());,和上面的Service申明的Action一致。BIND_AUTO_CREATE这个Flag从名字就能看出,表示如果Bind的时候,如果还没有Service的实例,就自动创建。
这里有一个地方需要注意,在Android 5.0以后,就不允许使用非特定的Intent来绑定Service了,需要使用如下方法:

Intent intent = new Intent(IRemoteService.class.getName());
intent.setClassName("com.race604.remoteservice", "com.race604.remoteservice.RemoteService");
// 或者setPackage()
// intent.setPackage("com.race604.remoteservice");
bindService(intent, mServiceConnection, BIND_AUTO_CREATE);

到这里就基本实现了一个完整的Client调用远程Service的实例了。

源代码可以参考这个Commit

Android Service实现双向通信(一)的更多相关文章

  1. android service两种启动方式

    android service的启动方式有以下两种: 1.Context.startService()方式启动,生命周期如下所示,启动时,startService->onCreate()-> ...

  2. 1、Android Studio集成极光推送(Jpush) 报错 java.lang.UnsatisfiedLinkError: cn.jpush.android.service.PushProtoco

    Android studio 集成极光推送(Jpush) (华为手机)报错, E/JPush: [JPushGlobal] Get sdk version fail![获取sdk版本失败!] W/Sy ...

  3. Android Service完全解析,关于服务你所需知道的一切(下)

    转载请注册出处:http://blog.csdn.net/guolin_blog/article/details/9797169 在上一篇文章中,我们学习了Android Service相关的许多重要 ...

  4. Android Service完全解析,关于服务你所需知道的一切(上)

    转载请注明出处:http://blog.csdn.net/guolin_blog/article/details/11952435 相信大多数朋友对Service这个名词都不会陌生,没错,一个老练的A ...

  5. android service 的各种用法(IPC、AIDL)

    http://my.oschina.net/mopidick/blog/132325 最近在学android service,感觉终于把service的各种使用场景和用到的技术整理得比较明白了,受益颇 ...

  6. Android service介绍和启动方式

    1.Android service的作用: service通常是用来处理一些耗时操作,或后台执行不提供用户交互界面的操作,例如:下载.播放音乐. 2.Android service的生命周期: ser ...

  7. Android Service初始

    一.Service概念 1.Service是一个应用程序组件 2.Service没有图像化界面 3.Service通常用来处理一些耗时比较长的操作 4.可以使用Service更新ContentProv ...

  8. Android Service与Thread的区别

    Android Service,后台,Android的后台就是指,它的运行是完全不依赖UI的.即使Activity被销毁,或者程序被关闭,只要进程还在,Service就可以继续运行.比如说一些应用程序 ...

  9. Android service binder aidl 关系

    /********************************************************************************** * Android servic ...

随机推荐

  1. 用Comparator排序和分组

    Test实体 import java.util.Objects; /** * @author gallen * @description * @date 2018/11/16 * @time 18:5 ...

  2. const用法归纳总结 C++

    非常好的一篇分析const的总结归纳, 在此谢谢原作者:http://blog.csdn.net/zcf1002797280/article/details/7816977 在普通的非 const成员 ...

  3. python基础补漏-07-正则表达式

    字符: .    匹配除了换行符以外的任意字符 \w  匹配字母或者数字或下划线或汉字(除了特殊字符外都能匹配) \s   匹配任意空白符 \d 匹配数字 \b 匹配单词的开始或者结束 ^ 匹配字符串 ...

  4. verilog 实现中值滤波

    图像信号在形成.传输和记录的过程中,由于成像系统.传输介质.工作环境和记录设备等的固有缺陷,不可避免地产生各种类型的噪声,降低了图像的质量,进而影响后续处理(如边缘检测.图像分割.特征提取.模式识别等 ...

  5. java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()解决办法

    代码改变世界 java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.pre ...

  6. JDBC 学习笔记(四)—— JDBC 加载数据库驱动,获取数据库连接

    1. 加载数据库驱动 通常来说,JDBC 使用 Class 类的 forName() 静态方法来加载驱动,需要输入数据库驱动代表的字符串. 例如: 加载 MySQL 驱动: Class.forName ...

  7. BZOJ3325 [Scoi2013]密码 【manacher】

    题目 Fish是一条生活在海里的鱼.有一天他很无聊,就到处去寻宝.他找到了位于海底深处的宫殿,但是一扇带有密码锁的大门却阻止了他的前进.通过翻阅古籍,Fish 得知了这个密码的相关信息: 该密码的长度 ...

  8. BZOJ1880 [Sdoi2009]Elaxia的路线 【最短路 + dp】

    题目 最近,Elaxia和w的关系特别好,他们很想整天在一起,但是大学的学习太紧张了,他们 必须合理地安排两个人在一起的时间.Elaxia和w每天都要奔波于宿舍和实验室之间,他们 希望在节约时间的前提 ...

  9. 【bzoj1717】[Usaco2006 Dec]Milk Patterns 产奶的模式 SA+二分

    Description 农夫John发现他的奶牛产奶的质量一直在变动.经过细致的调查,他发现:虽然他不能预见明天产奶的质量,但连续的若干天的质量有很多重叠.我们称之为一个“模式”. John的牛奶按质 ...

  10. Docker部署注册中心、Docker创建私有镜像库、自签名证书、Deploy a registry server

    这是我在内部部署Docker Registry时记录下来的笔记,操作环境是Centos 7.Docker 18.06.1-ce 1.运行registry 我当前所使用的主机的IP是192.168.1. ...