美文网首页
Service 和 Activity 如果想互发 Message

Service 和 Activity 如果想互发 Message

作者: 一洼世界 | 来源:发表于2017-02-27 13:40 被阅读378次

    Service 如何给 Activity 发送 Message 见《Activity 调用 Service 中的方法都有哪些方式?》题目中 Activity 跟 Service 绑定的第二种方式:Using a Messenger。
    考虑到官方只给出了 Activity 给 Service 发送 Message 的代码,在这里我给出一个 Activity 跟 Service 之间互相 发送 Message 通信的示例代码:

    1. MainActivity 代码
    package com.example.serviceAndActivity; 
    import android.os.Bundle;
    import android.os.Handler;
    import android.os.IBinder;
    import android.os.Message;
    import android.os.Messenger;
    import android.os.RemoteException;
    import android.app.Activity; 
    import android.app.Service;
    import android.content.ComponentName;
    import android.content.Intent;
    import android.content.ServiceConnection;
    import android.util.Log;
    import android.view.View;
    import android.widget.Toast;
    /**
    * Activity 和 Service 互发 Message *
    * @author wzy 2015-11-25
    *
    */
    public class MainActivity extends Activity {
    private Messenger messenger;
    //将该 Handler 发送 Service
    private Messenger mOutMessenger = new Messenger(new OutgoingHandler());
    @Override
    protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
    }
    // 绑定服务
    public void click1(View view) {
        Intent intent = new Intent(this, MessengerService.class);
        ServiceConnection conn = new MyServiceConnection();
        bindService(intent, conn, Service.BIND_AUTO_CREATE);
    }
    // 发送消息
    public void click2(View view) throws RemoteException {
        if (messenger == null) {
            Toast.makeText(this, "服务不可用!", Toast.LENGTH_SHORT).show();
    return; }
            Message message = new Message();
    message.obj="长江长江我是黄河"; message.what =0; messenger.send(message);
    }
    class OutgoingHandler extends Handler{
        @Override
        public void handleMessage(Message msg) {
                Log.d("tag", msg.toString());
    } }
    class MyServiceConnection implements ServiceConnection {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
              Toast.makeText(MainActivity.this, "连接成功!", Toast.LENGTH_SHORT).show(); messenger = new Messenger(service);
                Message message=new Message();
                message.what = 1;
                //Activity 绑定 Service 的时候给 Service 发送一个消息,该消息的 obj 属性是一个 Messenger 对象 message.obj = mOutMessenger;
                try {
                    messenger.send(message);
                } catch (RemoteException e) {
                    e.printStackTrace();
            }
      }
        @Override
        public void onServiceDisconnected(ComponentName name) {
            Toast.makeText(MainActivity.this, "连接已经断开!", Toast.LENGTH_SHORT).show(); }
          }
     }
    
    1. MessengerService 代码
    package com.example.serviceAndActivity;
    import android.app.Service;
    import android.content.Intent;
    import android.os.Handler;
    import android.os.IBinder;
    import android.os.Message;
    import android.os.Messenger;
    import android.os.RemoteException;
    import android.util.Log;
    /**
    * 该 Service 接收到 Activity 的消息后会在返回一条消息
     * @author wzy 2015-11-25
     *
     */
    public class MessengerService extends Service {
    private Messenger messenger = new Messenger(new IncomingHandler()); private Messenger mActivityMessenger ;
        @Override
        public IBinder onBind(Intent intent) {
            IBinder binder = messenger.getBinder();
            return binder;
        }
    //1.定义一个 Handler 对象,该 Handler 处理 Activity 发送过来的消息 class IncomingHandler extends Handler{
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                  case 0:
                        Log.d("tag", msg.toString());
                        if (mActivityMessenger!=null) {
                               Message message= new Message();
                               message.what = 2;
                              message.obj="地瓜地瓜我是土豆"; 
                            try {
                               mActivityMessenger.send(message);
                           } catch (RemoteException e) {
                               e.printStackTrace();
                           }
                  }
                      break;
                  case 1:
                          mActivityMessenger = (Messenger) msg.obj;
                          Log.d("tag", "已经获取到 Activity 发送了的 Messenger 对象");
                      break;
                  default:
                      break;
               }
            } }
    

    相关文章

      网友评论

          本文标题:Service 和 Activity 如果想互发 Message

          本文链接:https://www.haomeiwen.com/subject/chszwttx.html