我正在为我的
Android应用程序使用传感器.我用一行代码注册传感器:
mySensorManager.registerListener(this,orientationSensor,SensorManager.SENSOR_DELAY_NORMAL);
mySensorManager.unregisterListener(this);
到目前为止它工作,但我需要在应用程序恢复时再次注册它.我需要知道我的sensorManager是否有一个注册的监听器,所以我可以再次注册或skit它.这样的事情可以做到吗?:
if (mySensorManager.getRegisteredListenerList == null){ registerListener() } else { .. }
解决方法
据我所知,没有本地方法来检查您是否已经注册了监听器.我不会太担心这个检查,因为这个检查已经由Android完成,所以如果你已经注册了监听器,那么Android不会再添加两次相同的监听器:
@SuppressWarnings("deprecation") private boolean registerLegacyListener(int legacyType,int type,SensorListener listener,int sensors,int rate) { if (listener == null) { return false; } boolean result = false; // Are we activating this legacy sensor? if ((sensors & legacyType) != 0) { // if so,find a suitable Sensor Sensor sensor = getDefaultSensor(type); if (sensor != null) { // If we don't already have one,create a LegacyListener // to wrap this listener and process the events as // they are expected by legacy apps. LegacyListener legacyListener = null; synchronized (mLegacyListenersMap) { legacyListener = mLegacyListenersMap.get(listener); if (legacyListener == null) { // we didn't find a LegacyListener for this client,// create one,and put it in our list. legacyListener = new LegacyListener(listener); mLegacyListenersMap.put(listener,legacyListener); } } // register this legacy sensor with this legacy listener legacyListener.registerSensor(legacyType); // and finally,register the legacy listener with the new apis result = registerListener(legacyListener,sensor,rate); } } return result; }
因此,您可以根据需要多次调用registerListener,只会添加一次:)
这同样适用于取消注册逻辑