接上一篇的分析,今天继续
aidl复杂流程封装-CSDN博客
今天的任务就是将代码梳理下放进来
1 项目gradle配置:
需要将对应的代码放到各自的目录下,这里仅贴下关键内容,细节可以下载代码慢慢看
sourceSets {
main {
manifest.srcFile 'src/main/AndroidManifest.xml'
java.srcDirs = ['src/main/java']
aidl.srcDirs = ['src/main/aidl']
res.srcDirs = ['src/main/res']
assets.srcDirs = ['assets']
}
local {
java.srcDirs = ['src/local/java']
}
remote {
java.srcDirs = ['src/remote/java']
}
}
flavorDimensions "sdk"
productFlavors {
local {
dimension "sdk"
}
remote {
dimension "sdk"
}
}
2 aidl相关文件
1 客户端的回调接口:
interface ICallback {
void received(String params, in Bundle bundle);
}
2 aidl通信接口:
interface IServiceBinder {
int register(int version, String caller, ICallback callback);
void unregister(String caller, ICallback callback);
void received(String params, in Bundle bundle);
}
3 服务端(本地)代码
先看下对服务类的封装:增加服务端通知消息的入栈异步处理,防止服务端卡顿
(由于看板信息,播报信息,路况信息等数据频繁,需放入单独线程或线程池处理)
public abstract class AsynService extends Service {
protected static final String TAG = "JsonProtocolService";
protected WorkThread worker;
public void onCreate() {
super.onCreate();
if (this.worker == null || !this.worker.isRunning()) {
this.worker = new WorkThread();
this.worker.start();
}
}
public void onDestroy() {
super.onDestroy();
if (this.worker != null && this.worker.isRunning()) {
this.worker.interrupt();
this.worker = null;
}
}
protected String getRequestAuthor(String params) {
String requestAuthor = null;
try {
JSONObject jsonObject = new JSONObject(params);
if (jsonObject.has(SDKConstants.KEY_CLIENT_REQUEST_AUTHOR)) {
requestAuthor = jsonObject.optString(SDKConstants.KEY_CLIENT_REQUEST_AUTHOR);
}
} catch (JSONException e) {
Log.e(TAG, "getRequestAuthor: ", e);
}
return requestAuthor;
}
protected void offerReq(JsonProtocolManager.Message message) {
this.worker.offerReq(message);
}
//具体实现接口抽象出来给外部实现
public interface ServiceCallback {
void onEvent(int event, String msg);
String received(String params, Bundle bundle);
}
protected static class WorkThread extends Thread {
private static final Object syncObj = new Object();
private final LinkedBlockingQueue<JsonProtocolManager.Message> msgLBQ = new LinkedBlockingQueue<>();
private boolean isRunning = false;
private ServiceCallback serviceCallback;
public void init(ServiceCallback callback) {
synchronized(syncObj) {
this.serviceCallback = callback;
syncObj.notify();
}
}
public void onEvent(int event, String msg) {
synchronized(syncObj) {
if (this.serviceCallback != null) {
this.serviceCallback.onEvent(event, msg);
}
}
}
public void offerReq(JsonProtocolManager.Message message) {
this.msgLBQ.offer(message);
}
public void run() {
this.isRunning = true;
while (this.isRunning) {
try {
JsonProtocolManager.Message msg = this.msgLBQ.take();
synchronized(syncObj) {
while (this.serviceCallback == null) {
syncObj.wait();
}
}
if (!this.onReceive(msg)) {
this.msgLBQ.offer(msg);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
boolean isRunning