Http远程控制App
最近有项目需求通过远程http来控制android app,首先需要在app中内嵌http服务,开始考虑用jetty,后来发现有更加轻量级的NanoHttpd组件,GitHub地址:https://github.com/NanoHttpd/nanohttpd
用起来比较轻便,最终通过在启动app时启动一个Service 实例化NanoHttpd ,在开发中遇到一个问题就是App有多个Activity, Service 调用Activity 中的方法,可能大家想到最简单的做法是通过广播来实现,因为 Service和Activity属于两个进程,在android中最简单的进程调用就是通过广播来实现。
但是有个问题就是广播延迟比较严重,为了解决延迟问题。最终选择了通过两个AIDL 接口来实现,用一个AIDL作另一个的会调接口。具体做法如下:
IClientCallBack.aidl
// IClientCallBack.aidl
package com.test.application;
// Declare any non-default types here with import statements
interface IClientCallBack {
/**
* Demonstrates some basic types that you can use as parameters
* and return values in AIDL.
*/
int getResult(String action);
}
IGetData.aidl
// IGetData.aidl
package com.test.application;
import com.test.application.IClientCallBack;
// Declare any non-default types here with import statements
interface IGetData {
/**
* Demonstrates some basic types that you can use as parameters
* and return values in AIDL.
*/
void register(IClientCallBack callback);
}
MainService .java
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import com.test.application.IClientCallBack;
import com.test.application.IGetData;
import java.io.IOException;
/**
* MainService.
*/
public class MainService extends Service{
MainService mainService;
/**
* HttpServer.
*/
public static HttpServer mHttpServer = null;
public static IClientCallBack callBack;
@Nullable
@Override
public IBinder onBind(final Intent intent) {
return mBinder;
}
@Override
public boolean onUnbind(Intent intent) {
return super.onUnbind(intent);
}
@Override
public void onCreate() {
}
@Override
public void onDestroy() {
}
/*
* MsgBinder.
*/
public class MsgBinder extends Binder {
/**
* Service.
* @return Service
*/
public MainService getService() {
return MainService.this;
}
}
IGetData.Stub mBinder= new IGetData.Stub(){
@Override
public void register(IClientCallBack mcallback) throws RemoteException {
callBack = mcallback;
mHttpServer.setCallBack(callBack);
}
};
}