How to Build a Sensor Simulator for Android?

泪湿孤枕 提交于 2019-12-03 01:04:56

Well, it seems what you want to make is a application that will emulate the sensors on a Android device for your application while testing on the emulator.
Probably in your application, you have a line like this:

SensorManager mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);

Why not create a interface that has the methods you use from SensorManager:

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

    ... // You will need to add all the methods you use from SensorManager here
}

And then create a wrapper for SensorManager that just calls those methods on a real SensorManager object:

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()
}

And then create another MySensorManager, that this time communicates over a socket to a desktop application you will create where you enter the sensor values or something:

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
}

And finally, replace your first line:

SensorManager mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);

With a new line:

MySensorManager mSensorManager;
if(YOU_WANT_TO_EMULATE_THE_SENSOR_VALUES) {
    mSensorManager = new MyFakeSensorManager();
else {
    mSensorManager = new MySensorManagerWrapper((SensorManager)getSystemService(SENSOR_SERVICE));
}

Now you can just use that object instead of the SensorManager you used before.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!