如何为Android构建传感器模拟器?

Hug*_*ugo 10 simulation android sensor

我正在为Android平台构建应用程序,我想使用加速度计.现在,我已经找到了一个非常好的传感器仿真应用程序(OpenIntents的SensorSimulator),但是,对于我想要做的事情,我想创建自己的传感器模拟器应用程序.

我还没有找到关于如何做到这一点的信息(我不知道反汇编模拟器的jar是否正确),正如我所说,我想构建一个更小更简单的传感器模拟器版本,更适合我的意图.

你知道我从哪里开始吗?我在哪里可以看到我需要构建的代码片段是什么?

基本上,我只是想要一些方向.

Isa*_*ler 8

好吧,您想要制作的是一个应用程序,它将在模拟器上进行测试时为您的应用程序模拟Android设备上的传感器.
可能在您的应用程序中,您有一个这样的行:

SensorManager mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
Run Code Online (Sandbox Code Playgroud)

为什么不创建一个包含您在SensorManager中使用的方法的接口:

interface MySensorManager {
    List<Sensor> getSensorList(int type);

    ... // You will need to add all the methods you use from SensorManager here
}
Run Code Online (Sandbox Code Playgroud)

然后为SensorManager创建一个包装器,它只在真正的SensorManager对象上调用这些方法:

class MySensorManagerWrapper implements MySensorManager {
    SensorManager mSensorManager;

    MySensorManagerWrapper(SensorManager sensorManager) {
        super();
        mSensorManager = sensorManager;
    }

    List<Sensor> getSensorList(int type) {
         return mSensorManager.getSensorList(type_;
    }

    ... // All the methods you have in your MySensorManager interface will need to be defined here - just call the mSensorManager object like in getSensorList()
}
Run Code Online (Sandbox Code Playgroud)

然后创建另一个MySensorManager,这次通过套接字与您将在输入传感器值或其他内容时创建的桌面应用程序进行通信:

class MyFakeSensorManager implements MySensorManager {
    Socket mSocket;

    MyFakeSensorManager() throws UnknownHostException, IOException {
        super();
        // Connect to the desktop over a socket
        mSocket =  = new Socket("(IP address of your local machine - localhost won't work, that points to localhost of the emulator)", SOME_PORT_NUMBER);
    }

    List<Sensor> getSensorList(int type) {
        // Use the socket you created earlier to communicate to a desktop app
    }

    ... // Again, add all the methods from MySensorManager
}
Run Code Online (Sandbox Code Playgroud)

最后,替换你的第一行:

SensorManager mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
Run Code Online (Sandbox Code Playgroud)

新线:

MySensorManager mSensorManager;
if(YOU_WANT_TO_EMULATE_THE_SENSOR_VALUES) {
    mSensorManager = new MyFakeSensorManager();
else {
    mSensorManager = new MySensorManagerWrapper((SensorManager)getSystemService(SENSOR_SERVICE));
}
Run Code Online (Sandbox Code Playgroud)

现在您可以使用该对象而不是之前使用的SensorManager.