zoukankan      html  css  js  c++  java
  • 通过messenger实现activity与service的相互通信

    布局:

     1 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
     2     xmlns:tools="http://schemas.android.com/tools"
     3     android:layout_width="match_parent"
     4     android:layout_height="match_parent"
     5     tools:context="com.zzw.testmessenger.MainActivity" >
     6 
     7     <Button
     8         android:id="@+id/bind"
     9         android:layout_width="wrap_content"
    10         android:layout_height="wrap_content"
    11         android:layout_alignParentBottom="true"
    12         android:layout_alignParentLeft="true"
    13         android:text="绑定" />
    14 
    15     <Button
    16         android:id="@+id/send"
    17         android:layout_width="wrap_content"
    18         android:layout_height="wrap_content"
    19         android:layout_alignParentBottom="true"
    20         android:layout_alignParentRight="true"
    21         android:text="发送数据" />
    22 
    23     <Button
    24         android:id="@+id/start"
    25         android:layout_width="wrap_content"
    26         android:layout_height="wrap_content"
    27         android:layout_alignParentBottom="true"
    28         android:layout_centerHorizontal="true"
    29         android:text="加法" />
    30 
    31 </RelativeLayout>
    activity_main.xml

    MainActivity:

      1 package com.zzw.testmessenger;
      2 
      3 import android.app.Activity;
      4 import android.content.ComponentName;
      5 import android.content.Intent;
      6 import android.content.ServiceConnection;
      7 import android.os.Bundle;
      8 import android.os.Handler;
      9 import android.os.IBinder;
     10 import android.os.Message;
     11 import android.os.Messenger;
     12 import android.os.RemoteException;
     13 import android.util.Log;
     14 import android.view.View;
     15 import android.view.View.OnClickListener;
     16 import android.widget.Button;
     17 
     18 public class MainActivity extends Activity implements OnClickListener {
     19     Button bind, send, start;
     20     ServiceConnection sc;
     21     Messenger sender, receiver;
     22     int sum;
     23     Handler handler;
     24 
     25     @Override
     26     protected void onCreate(Bundle savedInstanceState) {
     27         super.onCreate(savedInstanceState);
     28         setContentView(R.layout.activity_main);
     29 
     30         bind = (Button) findViewById(R.id.bind);
     31         bind.setOnClickListener(this);
     32         send = (Button) findViewById(R.id.send);
     33         send.setOnClickListener(this);
     34         start = (Button) findViewById(R.id.start);
     35         start.setOnClickListener(this);
     36 
     37         handler = new Handler() {
     38             @Override
     39             public void handleMessage(Message msg) {
     40                 super.handleMessage(msg);
     41                 if (msg.what == 1) {
     42                     int sum = (Integer) msg.obj;
     43                     Log.d("收到服务器传来的消息--->", sum + "");
     44                 }
     45             }
     46         };
     47         //activity接收serviece的数据的接收者
     48         receiver = new Messenger(handler);
     49     }
     50 
     51     @Override
     52     public void onClick(View v) {
     53         switch (v.getId()) {
     54         case R.id.bind:
     55             bindService();
     56             break;
     57         case R.id.send:
     58             sendMessageToService();
     59             break;
     60         case R.id.start:
     61             StartService();
     62             break;
     63         }
     64     }
     65 
     66     private void bindService() {
     67         sc = new ServiceConnection() {
     68             @Override
     69             public void onServiceDisconnected(ComponentName name) {
     70             }
     71 
     72             @Override
     73             public void onServiceConnected(ComponentName name, IBinder service) {
     74                 //activity向serviece的发送数据的发送者
     75                 sender = new Messenger(service);
     76             }
     77         };
     78         Intent intent = new Intent(MainActivity.this, MessengerService.class);
     79         bindService(intent, sc, BIND_AUTO_CREATE);
     80     }
     81 
     82     private void StartService() {
     83         Intent it = new Intent(MainActivity.this, MessengerService.class);
     84         startService(it);
     85     }
     86 
     87     private void sendMessageToService() {
     88         try {
     89             Message msg = new Message();
     90             int a = (int) (Math.random() * 20);
     91             int b = (int) (Math.random() * 20);
     92             int s[] = { a, b };
     93 
     94             msg.what = 0;
     95             msg.obj = s;
     96 
     97             // 设置一个Messenger receiver,receiver是提供给Service使用来给Activity响应的目标。
     98             msg.replyTo = receiver;
     99             sender.send(msg);
    100 
    101             Log.d("sendMessageToService", "发送成功----->");
    102         } catch (RemoteException e) {
    103             e.printStackTrace();
    104         }
    105     }
    106 
    107     @Override
    108     protected void onDestroy() {
    109         unbindService(sc);
    110         Intent intent = new Intent(MainActivity.this, MessengerService.class);
    111         stopService(intent);
    112         super.onDestroy();
    113     }
    114 }

    MessengerService:

     1 package com.zzw.testmessenger;
     2 
     3 import android.app.Service;
     4 import android.content.Intent;
     5 import android.os.Handler;
     6 import android.os.IBinder;
     7 import android.os.Message;
     8 import android.os.Messenger;
     9 import android.os.RemoteException;
    10 import android.util.Log;
    11 
    12 public class MessengerService extends Service {
    13     private Messenger messenger, sender;
    14     Handler handler;
    15     int a, b, sum;
    16 
    17     @Override
    18     public void onCreate() {
    19         Log.d("MessengerSerivice", "onCreate");
    20         handler = new Handler() {
    21             @Override
    22             public void handleMessage(Message msg) {
    23                 super.handleMessage(msg);
    24                 if (msg.what == 0) {
    25                     int[] s = (int[]) msg.obj;
    26                     a = s[0];
    27                     b = s[1];
    28                     Log.d("从activity收到的msg", "a=" + a + "  b=" + b);
    29                 }
    30                 //service向activity发送数据的发送者
    31                 sender = msg.replyTo;
    32             }
    33         };
    34         //service接收activity的数据的接收者
    35         messenger = new Messenger(handler);
    36     }
    37 
    38     private void sendMessageToActivity(Messenger sender) {
    39         try {
    40             Message msg = new Message();
    41             msg.what = 1;
    42             msg.obj = sum;
    43             sender.send(msg);
    44             Log.d("sendMessageToActivity", "成功发送");
    45         } catch (RemoteException e) {
    46             // TODO Auto-generated catch block
    47             e.printStackTrace();
    48         }
    49     }
    50 
    51     @Override
    52     public int onStartCommand(Intent intent, int flags, int startId) {
    53         Log.d("MessengerSerivice", "onStartCommand");
    54         sum = a + b;
    55         Log.d("在onStartCommand中算出的和", sum + "");
    56         sendMessageToActivity(sender);
    57         
    58         return super.onStartCommand(intent, flags, startId);
    59     }
    60 
    61     @Override
    62     public IBinder onBind(Intent intent) {
    63         Log.d("MessengerSerivice", "onBind");
    64         return messenger.getBinder();
    65     }
    66 
    67 }
  • 相关阅读:
    HDU 跑跑卡丁车
    螺旋模型
    原型模型
    CSS匹配规则参考
    索引调优
    动态加载外部css或js文件
    des算法的C#实现
    @@RowCount和“SET NOCOUNT ON”在触发器中使用的先后顺序引起的问题
    WebService生成XML文档时出错。不应是类型XXXX。使用XmlInclude或SoapInclude属性静态指定非已知的类型。
    Sql获取星期几的方法
  • 原文地址:https://www.cnblogs.com/zzw1994/p/4953242.html
Copyright © 2011-2022 走看看