好吧,您似乎想要制作一个应用程序,该应用程序将在模拟器上进行测试时为您的应用程序模拟 Android 设备上的传感器。
可能在您的应用程序中,您有这样的一行:
SensorManager mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
为什么不创建一个具有您在 SensorManager 中使用的方法的接口:
interface MySensorManager {
List<Sensor> getSensorList(int type);
... // You will need to add all the methods you use from SensorManager here
}
然后为 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()
}
然后创建另一个 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
}
最后,替换您的第一行:
SensorManager mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
换行:
MySensorManager mSensorManager;
if(YOU_WANT_TO_EMULATE_THE_SENSOR_VALUES) {
mSensorManager = new MyFakeSensorManager();
else {
mSensorManager = new MySensorManagerWrapper((SensorManager)getSystemService(SENSOR_SERVICE));
}
现在您可以只使用该对象而不是之前使用的 SensorManager。