如果你需要你的service和其他进程通信,那么你可以使用一个Messenger来提供这个接口。

这种方法允许你在不使用 AIDL的情况下,进行跨进程通信IPC。

实现步骤

下面是一个如何使用 Messenger的小总结:

  1. service实现一个 Handler 接收客户端每一次调用的回调。

  2. Handler 用来创建一个Messenger对象,它是一个Handler的引用。

  3. Messenger创建一个 IBinder,service从 onBind()中把它返回给客户端。

  4. 客户端使用这个IBinder来实例化Messenger (service的Handler的引用),客户端使用它来向service发送Message对象。

  5. service在它的Handler中接收每一个Message对象,在它的 handleMessage()方法中。

Code

public class MessengerService extends Service
{
/** Command to the service to display a message */
static final int MSG_SAY_HELLO = 1; /**
* Handler of incoming messages from clients.
*/
class IncomingHandler extends Handler
{
@Override
public void handleMessage(Message msg)
{
switch (msg.what)
{
case MSG_SAY_HELLO:
Toast.makeText(getApplicationContext(), "hello!",
Toast.LENGTH_SHORT).show();
break;
default:
super.handleMessage(msg);
}
}
} /**
* Target we publish for clients to send messages to IncomingHandler.
*/
final Messenger mMessenger = new Messenger(new IncomingHandler()); /**
* When binding to the service, we return an interface to our messenger for
* sending messages to the service.
*/
@Override
public IBinder onBind(Intent intent)
{
Toast.makeText(getApplicationContext(), "binding", Toast.LENGTH_SHORT)
.show();
return mMessenger.getBinder();
}
}

  注意 Handler中的 handleMessage() 方法是service接收到来的 Message并且决定做什么的地方。

  客户端需要做的仅仅是创建一个基于service所返回的 IBinder的 Messenger,然后用 send()方法发送信息。

  比如,这里有一个简单的activity和service绑定并且发送信息给service:

public class ActivityMessenger extends Activity
{
/** Messenger for communicating with the service. */
Messenger mService = null; /** Flag indicating whether we have called bind on the service. */
boolean mBound; /**
* Class for interacting with the main interface of the service.
*/
private ServiceConnection mConnection = new ServiceConnection()
{
public void onServiceConnected(ComponentName className, IBinder service)
{
// This is called when the connection with the service has been
// established, giving us the object we can use to
// interact with the service. We are communicating with the
// service using a Messenger, so here we get a client-side
// representation of that from the raw IBinder object.
mService = new Messenger(service);
mBound = true;
} public void onServiceDisconnected(ComponentName className)
{
// This is called when the connection with the service has been
// unexpectedly disconnected -- that is, its process crashed.
mService = null;
mBound = false;
}
}; public void sayHello(View v)
{
if (!mBound)
return;
// Create and send a message to the service, using a supported 'what'
// value
Message msg = Message
.obtain(null, MessengerService.MSG_SAY_HELLO, 0, 0);
try
{
mService.send(msg);
}
catch (RemoteException e)
{
e.printStackTrace();
}
} @Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
} @Override
protected void onStart()
{
super.onStart();
// Bind to the service
bindService(new Intent(this, MessengerService.class), mConnection,
Context.BIND_AUTO_CREATE);
} @Override
protected void onStop()
{
super.onStop();
// Unbind from the service
if (mBound)
{
unbindService(mConnection);
mBound = false;
}
}
}

  注意这个例子并没有展示service如何响应客户端,如果你想要service响应,你需要在客户端中创建一个 Messenger。

  然后当客户端接收到onServiceConnected()回调方法时,它会发送一个 Message到service,在它的send() 方法的replyTo参数中包含了客户端的Messenger。

Android -- Messager与Service的更多相关文章

  1. Android 面试题--Service

    1.Service 是否在 main thread 中执行, service 里面是否能执行耗时的操作?默认情况,如果没有显示的指 servic 所运行的进程, Service 和 activity ...

  2. Android探索之Service全面回顾及总结

    什么是Service? Service(服务)是Android提供的四大组件之一,是一个没有用户界面的在后台运行执行耗时操作的应用组件.其他应用组件能够启动Service,并且当用户切换到另外的应用场 ...

  3. Android 中的 Service 全面总结(转载)

    转载地址:http://www.cnblogs.com/newcj/archive/2011/05/30/2061370.html 感谢作者 Android 中的 Service 全面总结 1.Ser ...

  4. java攻城狮之路(Android篇)--BroadcastReceiver&Service

    四大组件:activity 显示. contentProvider 对外暴露自己的数据给其他的应用程序.BroadcastReceiver 广播接收者,必须指定要接收的广播类型.必须明确的指定acti ...

  5. 图解Android - Binder 和 Service

    在 Zygote启动过程 一文中我们说道,Zygote一生中最重要的一件事就是生下了 System Server 这个大儿子,System Server 担负着提供系统 Service的重任,在深入了 ...

  6. Android 服务类Service 的详细学习

    http://blog.csdn.net/vipzjyno1/article/details/26004831 Android服务类Service学习四大组建   目录(?)[+] 什么是服务 服务有 ...

  7. 大仙说道之Android studio实现Service AIDL

    今天要开发过程中要用到AIDL的调用,之前用的eclipse有大量教程,用起来很方便,现在刚换了Android studio,不可否认studio真的很强大,只是很多功能还需要摸索. AIDL(And ...

  8. Android四大组件——Service

    Service相关链接 Service初涉 Service进阶 Service精通 Service是Android系统中的一种组件,它跟Activity的级别差不多,但是它不能自己运行,只能后台运行, ...

  9. Android学习总结——Service组件

    从Service的启动方式上,可以将Service分为Started Service和Bound Service.在使用Service时,要想系统能够找到此自定义Service,无论哪种类型,都需要在 ...

随机推荐

  1. centos 给终端设快捷键

    centos 终端的快捷键是默认是禁用的 设置的话 系统-> 首选项 -> 键盘快捷键 看到运行终端    随便设置想要的快捷键!!

  2. 141 Linked List Cycle(判断链表是否有环Medium)

    题目意思:链表有环,返回true,否则返回false 思路:两个指针,一快一慢,能相遇则有环,为空了没环 ps:很多链表的题目:都可以采用这种思路 /** * Definition for singl ...

  3. Bootstrap_排版_标题

    Bootstrap和普通的HTML页面一样,定义标题都是使用标签<h1>到<h6>,只不过Bootstrap覆盖了其默认的样式,使用其在所有浏览器下显示的效果一样,具体定义的规 ...

  4. window.clearInterval与window.setInterval的用法 定时器的设置

    window.setInterval() 功能:按照指定的周期(以毫秒计)来调用函数或计算表达式. 语法:setInterval(code,millisec) code:在指定时间到时要执行的Java ...

  5. CSU 1337(费马大定理)

      CSU 1337 Time Limit:1000MS     Memory Limit:131072KB     64bit IO Format:%lld & %llu   Descrip ...

  6. 变量-if else while-运算符

    变量: SQL语言也跟其他编程语言一样,拥有变量.分支.循环等控制语句. 在SQL语言里面把变量分为局部变量和全局变量,全局变量又称系统变量. 局部变量: 使用declare关键字给变量声明,语法非常 ...

  7. Coupons

    uva10288:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=24&am ...

  8. 【HDOJ】2604 Queuing

    递推,推得f(n) = f(n-1) + f(n-3) + f(n-4).然后转换成矩阵相乘,如下f(n-1)  f(n-2)  f(n-3)  f(n-4)   *    1   1   0   0 ...

  9. Java的内存管理与内存泄露

    作为Internet最流行的编程语言之一,Java现正非常流行.我们的网络应用程序就主要采用Java语言开发,大体上分为客户端.服务器和数据库三个层次.在进入测试过程中,我们发现有一个程序模块系统内存 ...

  10. 《SDN核心技术剖析和实战指南》2.3 OF-CONFIG配置管理协议小结

    OpenFlow协议定义了交换机和控制器交换数据的方式和规范,但并没有定义如何配置和管理必需的网络参数和网络资源,OF-CONFIG的提出就是为了对OpenFlow提供配置管理支持.如下图所示,OF- ...