aidl远程调用绑定式Service,和Activity实现数据交互

1、定义PackMsg.aidl,承载数据的实体类

// PackMsg.aidl
package com.example.kervin.parse;

// Declare any non-default types here with import statements

parcelable PackMsg;

2、定义IBufferRcvCallback.aidl,接口类,将Service中的数据回调到Activity中来

// IBufferRcvCallback.aidl
package com.example.kervin.parse;

import com.example.kervin.parse.PackMsg;

// Declare any non-default types here with import statements

interface IBufferRcvCallback {

    void onFindFrame(in PackMsg packMsg);
}

3、定义IBufferManagerService.aidl,接口类,在Activity端发送数据到Service,和在Activity端注册和取消注册IBufferRcvCallback接口

// IBufferManagerService.aidl
package com.example.kervin.parse;

import com.example.kervin.parse.IBufferRcvCallback;
import com.example.kervin.parse.PackMsg;

// Declare any non-default types here with import statements

interface IBufferManagerService {

    boolean sendBuf(in PackMsg packMsg);
    void registerBufRcvCallback(IBufferRcvCallback callBack);
    void unRegisterBufRcvCallback(IBufferRcvCallback callBack);
}

4、编译

5、在生成的PackMsg.java文件中实现相应操作:
注:此类必须实现Parcelable接口

package com.example.kervin.parse;

import android.os.Parcel;
import android.os.Parcelable;

/**
 * Created by Android Studio.
 * User: lidongdong
 * Date: 2019/7/26
 * Time: 14:32
 */
public class PackMsg implements Parcelable {

    //重发次数
    private int reSendCount = 0;
    //序号
    private int msgSeq = 0;
    //协议index
    private int protocolType = -1;
    //数据通道Index
    private int channelType = -1;
    //数据数组
    private byte[] data;

    public PackMsg(byte[] data) {
        this.data = data;
    }

    public PackMsg(byte[] data, int channelType, int protocolType) {
        this.protocolType = protocolType;
        this.channelType = channelType;
        this.data = data;
    }

    public int getReSendCount() {
        return reSendCount;
    }

    public int getMsgSeq() {
        return msgSeq;
    }

    public int getProtocolType() {
        return protocolType;
    }

    public int getChannelType() {
        return channelType;
    }

    public byte[] getData() {
        return data;
    }

    public PackMsg(Parcel in) {
        reSendCount = in.readInt();
        msgSeq = in.readInt();
        protocolType = in.readInt();
        channelType = in.readInt();
        in.readByteArray(data);
    }

    public void setMsgSeq(int msgSeq) {
        this.msgSeq = msgSeq;
    }

    //必须提供一个名为CREATOR的static final属性 ,
    //该属性需要实现android.os.Parcelable.Creator<T>接口
    public static final Creator<PackMsg> CREATOR = new Creator<PackMsg>() {
        @Override
        public PackMsg createFromParcel(Parcel source) {
            return new PackMsg(source);
        }
        @Override
        public PackMsg[] newArray(int size) {
            return new PackMsg[size];
        }
    };
    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(reSendCount);
        dest.writeInt(msgSeq);
        dest.writeInt(protocolType);
        dest.writeInt(channelType);
        dest.writeByteArray(data);
    }

    public void readFromParcel(Parcel reply) {
        reSendCount = reply.readInt();
        msgSeq = reply.readInt();
        protocolType = reply.readInt();
        channelType = reply.readInt();
        reply.readByteArray(data);
    }

}

5、service

package com.example.kervin.parse;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class BufferService extends Service {

    private LocalConfigServer mLocalConfigServer = new LocalConfigServer();

    private List<IBufferRcvCallback> mIBufRcvCallBackList = new ArrayList<>();

    IBufferManagerService.Stub mIBufService = new IBufferManagerService.Stub() {
        @Override
        public boolean sendBuf(PackMsg packMsg) throws RemoteException {
        	//收到Activity中传递过去的数据buf
            return sendMsg(packMsg);
        }

        @Override
        public void registerBufRcvCallback(IBufferRcvCallback callBack) throws RemoteException {
            if (!mIBufRcvCallBackList.contains(callBack)) {
                mIBufRcvCallBackList.add(callBack);
            }
        }

        @Override
        public void unRegisterBufRcvCallback(IBufferRcvCallback callBack) throws RemoteException {
            if (mIBufRcvCallBackList.contains(callBack)) {
                mIBufRcvCallBackList.remove(callBack);
            }
        }
    };

    @Override
    public void onCreate() {
        super.onCreate();
        LogUtil.d("onCreate");
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        LogUtil.d("onBind : intent = " + intent.toString());
        return mIBufService;
    }

    public void onGotPackage(byte[] packData) {
        LogUtil.d("onGotPackage len = " + packData.length);
       //将数据打包成PackMsg对象,回传到Activity中
        PackMsg packMsg = new PackMsg(packData);
        for (IBufferRcvCallback callback : mIBufRcvCallBackList) {
            try {
                callback.onFindFrame(packMsg);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }

    private boolean sendMsg(PackMsg packMsg) {
        byte[] sendBuf = packMsg.getData();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        LogUtil.d("onDestroy");
        
    }
}

5、Activity绑定service

package com.example.kervin.demo;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;

import com.example.kervin.parse.BufferService;
import com.example.kervin.parse.IBufferManagerService;
import com.example.kervin.parse.IBufferRcvCallback;
import com.example.kervin.parse.PackMsg;
import com.example.kervin.parse.utils.HexTools;
import com.example.kervin.parse.utils.LogUtil;

/**
 * Created by Android Studio.
 * User: lidongdong
 * Date: 2019/9/9
 * Time: 11:01
 *
 * 要在Manifest文件中注册service
 * <service
 *    android:name="com.example.kervin.parse.BufferService"
 *    android:enabled="true"
 *    android:exported="true" />
 */
public abstract class FrameBaseActivity extends Activity {

    public static final int BASE_MSG_ID = 1;
    public static final int RCV_FRAME_MSG_ID = BASE_MSG_ID + 1;
    public static final int FRAME_TIME_OUT_MSG_ID = BASE_MSG_ID + 2;
    public static final int FRAME_RESEND_MSG_ID = BASE_MSG_ID + 3;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case RCV_FRAME_MSG_ID:
                    byte[] data = ((PackMsg)msg.obj).getData();

                    mHandler.removeMessages(FRAME_TIME_OUT_MSG_ID);
                    mHandler.removeMessages(FRAME_RESEND_MSG_ID);

                    FrameBaseActivity.this.onGotFrame(data);
                    break;

                case FRAME_TIME_OUT_MSG_ID:
                    FrameBaseActivity.this.onTimeOut();
                    break;

                case FRAME_RESEND_MSG_ID:
                    FrameBaseActivity.this.sendPackMsg((byte[]) msg.obj, msg.arg1, msg.arg2);
                    break;
            }
        }

    };

    /**
     * 被调用的方法运行在Binder线程池中,不能更新UI
	 * 此处收到Service中传递回来的数据
     */
    private IBufferRcvCallback mIBufferRcvCallback = new IBufferRcvCallback.Stub() {
        @Override
        public void onFindFrame(PackMsg packMsg) throws RemoteException {
            LogUtil.d("onFindFrame : " + HexTools.byteArrayToHex(packMsg.getData()));
            if (mHandler != null) {
                Message msg = mHandler.obtainMessage(RCV_FRAME_MSG_ID);
                msg.obj = packMsg;
                mHandler.sendMessage(msg);
            }
        }
    };

    private IBufferManagerService mIBufService;
    private ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mIBufService = IBufferManagerService.Stub.asInterface(service);
            try {
				//给service注册数据回调接口
                mIBufService.registerBufRcvCallback(mIBufferRcvCallback);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mIBufService = null;
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Intent intent = new Intent(this, BufferService.class);
        bindService(intent, mServiceConnection, BIND_AUTO_CREATE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mIBufService != null && mIBufService.asBinder().isBinderAlive()) {
            try {
                mIBufService.unRegisterBufRcvCallback(mIBufferRcvCallback);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        unbindService(mServiceConnection);
    }

    /**
     * 发送报文给远程服务
     * @param data
     * @return
     */
    public boolean sendPackMsg(byte[] data) {
        boolean sendOk = false;
        PackMsg packMsg = new PackMsg(data);

        if (mIBufService != null) {
            try {
                sendOk = mIBufService.sendBuf(packMsg);
            } catch (RemoteException e) {
                e.printStackTrace();
                sendOk = false;
            }
        }
        return sendOk;
    }

    /**
     * 解析到一帧数据
     * @param data
     */
    public abstract void onGotFrame(byte[] data);

    /**
     * 发出消息后,无回复,超时
     */
    public abstract void onTimeOut();


}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值