133_Activity调用Service方法


Activity调用Service方法有哪些方式


1.Extending the Binder class

通过Binder接口的形式实现,

Activity绑定Service成功的时候

Activity会在ServiceConnection的类的onServiceConnected()回调方法中

获取到ServiceonBind()方法

return过来的Binder的子类

 

 


2.Using a Messenger

 

这方法好像很复杂

我们来看看官方的示例

 

If you need your interface to work across different processes, you can create an interface for the service

with a Messenger. In this manner, the service defines a Handler that responds to different types of Message

objects. This Handler is the basis for a Messenger that can then share an IBinder with the client, allowing

the client to send commands to the service using Message objects. Additionally, the client can define

a Messenger of its own so the service can send messages back.

 

如果你需要你的接口在不同的进程工作,你可以创建一个用Messenger来创建一个接口

在这种方式下,服务定义了一个Handler,对不同的Message对象作出响应

这个HandlerMessenger的基础,可以跟client分享一个IBinder,

允许clientMessage对象来给服务发送命令

另外,clinet可以定义自己定义一个Messenger,这样服务就可以发回messages.

 

 

This is the simplest way to perform interprocess communication (IPC), because the Messenger queues all

requests into a single thread so that you don't have to design your service to be thread-safe.

 

这是进行进程间通信IPC最简单的方法,因为Messenger队列全都对单独一个线程请求

所以不用设置Service为线程安全

 

Here's a summary of how to use a Messenger:

l The service implements a Handler that receives a callback for each call from a client.

l The Handler is used to create a Messenger object (which is a reference to the Handler).

l The Messenger creates an IBinder that the service returns to clients from onBind().

l Clients use the IBinder to instantiate the Messenger (that references the service's Handler),

which the client uses to send Message objects to the service.

The service receives each Message in its Handlerspecifically, in the handleMessage() method.

In this way, there are no "methods" for the client to call on the service. Instead, the client delivers "messages" (Message objects) that the service receives in its Handler.

 

这里是如何使用Messenger的概要

1.service实现一个Handler,这个Handler接收一个对client的任意一个调用的回调

2.Handler被用来创建Messenger对象(Handler的一个参数)

3.Messenger创建一个IBinder,这个IBinderserviceonBind方法返回给clients

4.ClientsIBinder去实例化Messenger(serviceHandler的参数)

5.服务接收每个HandlerMessage,注意:是在handleMessge()方法中

 

这样,在服务中client没有方法可以调用,但是,client传递了messages(Message对象),就是serviceHandler接收的对象.

 

 

 

l

Here's a simple example service that uses a Messenger interface:

下面是官方实例

1. public class MessengerService extends Service {

2. /** Command to the service to display a message */

3. static final int MSG_SAY_HELLO = 1;

4.

5. /**

6. * Handler of incoming messages from clients.

7. */

8. class IncomingHandler extends Handler {

9. @Override

10. public void handleMessage(Message msg) {

11. switch (msg.what) {

12. case MSG_SAY_HELLO:

13. Toast.makeText(getApplicationContext(),

14. "hello!", Toast.LENGTH_SHORT).show();

15. break;

16. default:

17. super.handleMessage(msg);

18. }

19. }

20. }

21.

22. /**

23. * Target we publish for clients to send messages to IncomingHandler.

24. */

25. final Messenger mMessenger = new Messenger(new IncomingHandler());

26.

27. /**

28. * When binding to the service, we return an interface to our messenger

29. * for sending messages to the service.

30. */

31. @Override

32. public IBinder onBind(Intent intent) {

33. Toast.makeText(getApplicationContext(),

34. "binding", Toast.LENGTH_SHORT).show();

35. return mMessenger.getBinder();

36. }

37. }

Notice that the handleMessage() method in the Handler is where the service receives the incoming Message

and decides what to do, based on the what member.

All that a client needs to do is create a Messenger based on the IBinder returned by the service and

send a message using send(). For example, here's a simple activity that binds to the service and delivers the MSG_SAY_HELLO message to the service:

1. public class ActivityMessenger extends Activity {

2. /** Messenger for communicating with the service. */

3. Messenger mService = null;

4.

5. /** Flag indicating whether we have called bind on the service. */

6. boolean mBound;

7.

8. /**

9. * Class for interacting with the main interface of the service.

10. */

11. private ServiceConnection mConnection = new ServiceConnection() {

12. public void onServiceConnected(ComponentName className, IBinder service) {

13. // This is called when the connection with the service has been

14. // established, giving us the object we can use to

15. // interact with the service. We are communicating with the

16. // service using a Messenger, so here we get a client-side

17. // representation of that from the raw IBinder object.

18. mService = new Messenger(service);

19. mBound = true;

20. }

21.

22. public void onServiceDisconnected(ComponentName className) {

23. // This is called when the connection with the service has been

24. // unexpectedly disconnected -- that is, its process crashed.

25. mService = null;

26. mBound = false;

27. }

28. };

29.

30. public void sayHello(View v) {

31. if (!mBound) return;

32. // Create and send a message to the service, using a supported 'what' value

33. Message msg = Message.obtain(null, MessengerService.MSG_SAY_HELLO, 0, 0);

34. try {

35. mService.send(msg);

36. } catch (RemoteException e) {

37. e.printStackTrace();

38. }

39. }

40.

41. @Override

42. protected void onCreate(Bundle savedInstanceState) {

43. super.onCreate(savedInstanceState);

44. setContentView(R.layout.main);

45. }

46.

47. @Override

48. protected void onStart() {

49. super.onStart();

50. // Bind to the service

51. bindService(new Intent(this, MessengerService.class), mConnection,

52. Context.BIND_AUTO_CREATE);

53. }

54.

55. @Override

56. protected void onStop() {

57. super.onStop();

58. // Unbind from the service

59. if (mBound) {

60. unbindService(mConnection);

61. mBound = false;

62. }

63. }

64. }

Notice that this example does not show how the service can respond to the client. If you want the service

to respond, then you need to also create a Messenger in the client. Then when the client receives the

onServiceConnected() callback, it sends a Message to the service that includes the client's Messenger

in the replyTo parameter of the send() method.

 

 

 

 

3.AIDL

详见127篇博客哦

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值