直接上代码
23. public class MainActivity extends Activity {
24. private Messenger messenger;
25. //将该 Handler 发送 Service
26. private Messenger mOutMessenger = new Messenger(new OutgoingHandler());
27.
28. @Override
29. protected void onCreate(Bundle savedInstanceState) {
30. super.onCreate(savedInstanceState);
31. setContentView(R.layout.activity_main);
32. }
33. // 绑定服务
34. public void click1(View view) {
35. Intent intent = new Intent(this, MessengerService.class);
36. ServiceConnection conn = new MyServiceConnection();
37. bindService(intent, conn, Service.BIND_AUTO_CREATE);
38. }
39.
40. // 发送消息
41. public void click2(View view) throws RemoteException {
42. if (messenger == null) {
43. Toast.makeText(this, "服务不可用!", Toast.LENGTH_SHORT).show();
44. return;
45. }
46. Message message = new Message();
47. message.obj="长江长江我是黄河";
48. message.what =0;
49. messenger.send(message);
50.
51. }
52.
53. class OutgoingHandler extends Handler{
54. @Override
55. public void handleMessage(Message msg) {
56. Log.d("tag", msg.toString());
57. }
58. }
59.
60. class MyServiceConnection implements ServiceConnection {
61.
62. @Override
63. public void onServiceConnected(ComponentName name, IBinder service) {
64. Toast.makeText(MainActivity.this, "连接成功!", Toast.LENGTH_SHORT).show();
65. messenger = new Messenger(service);
66. Message message=new Message();
67. message.what = 1;
68. //Activity 绑定 Service 的时候给 Service 发送一个消息,该消息的 obj 属性是一个 Messenger 对象
69. message.obj = mOutMessenger;
70. try {
71. messenger.send(message);
72. } catch (RemoteException e) {
73. e.printStackTrace();
74. }
75. }
76.
77. @Override
78. public void onServiceDisconnected(ComponentName name) {
79. Toast.makeText(MainActivity.this, "连接已经断开!", Toast.LENGTH_SHORT).show();
80. }
81.
82. }
83.
84. }
看着很复杂
其实认真仔细地看一遍,很简单
1个OutgoingHandler 继承 Handler
1个MyServiceConnection 实现 ServiceConnection
覆写一下handleMessage方法
覆写一下onServiceConnected,和onServiceDisconnected方法
一个就是服务连接成功,一个就是服务连接断开
那么就在onServiceConnected服务连接成功后给service发送一个消息
messenger=new Messenger(service);
messenger.send(message);
就这么简单
click1里面绑定服务
bindService
click2里面用messenger给service发消息