android.hardware.SensorManager Java Examples

The following examples show how to use android.hardware.SensorManager. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SensorChange.java    From VirtualSensor with GNU Lesser General Public License v3.0 7 votes vote down vote up
private float[] getGyroscopeValues(float timeDifference) {
    float[] angularRates = new float[] {0.0F, 0.0F, 0.0F};
    float[] rotationMatrix = new float[9];
    float[] gravityRot = new float[3];
    float[] angleChange = new float[3];

    SensorManager.getRotationMatrix(rotationMatrix, null, this.accelerometerValues, this.magneticValues);
    gravityRot[0] = GRAVITY[0] * rotationMatrix[0] + GRAVITY[1] * rotationMatrix[3] + GRAVITY[2] * rotationMatrix[6];
    gravityRot[1] = GRAVITY[0] * rotationMatrix[1] + GRAVITY[1] * rotationMatrix[4] + GRAVITY[2] * rotationMatrix[7];
    gravityRot[2] = GRAVITY[0] * rotationMatrix[2] + GRAVITY[1] * rotationMatrix[5] + GRAVITY[2] * rotationMatrix[8];
    SensorManager.getRotationMatrix(rotationMatrix, null, gravityRot, this.magneticValues);

    SensorManager.getAngleChange(angleChange, rotationMatrix, this.prevRotationMatrix);
    angularRates[0] = -(angleChange[1]) / timeDifference;
    angularRates[1] = (angleChange[2]) / timeDifference;
    angularRates[2] = (angleChange[0]) / timeDifference;

    this.prevRotationMatrix = rotationMatrix;
    return angularRates;
}
 
Example #2
Source File: AndroidSensor.java    From ssj with GNU General Public License v3.0 7 votes vote down vote up
/**
*
   */
  @Override
  protected boolean connect() throws SSJFatalException
  {
      manager = (SensorManager) SSJApplication.getAppContext().getSystemService(Context.SENSOR_SERVICE);

      boolean ok = true;
      for(SensorListener l : listeners)
      {
          Sensor s = manager.getDefaultSensor(l.getType().getType());
          if (s == null)
          {
              Log.e(l.getType().getName() + " not found on device");
              ok = false;
          }
          else
          {
              ok &= manager.registerListener(l, s, options.sensorDelay.get());
          }
      }

      return ok;
  }
 
Example #3
Source File: ProximitySensor.java    From AcDisplay with GNU General Public License v2.0 7 votes vote down vote up
@Override
public void onStart(@NonNull SensorManager sensorManager) {
    if (DEBUG) Log.d(TAG, "Starting proximity sensor...");

    mHistory.clear();
    mHistory.add(new Event(false, getTimeNow()));

    Config.getInstance().registerListener(this);
    updateWave2WakeProgram();

    // Ignore pocket program's start delay,
    // so app can act just after it has started.
    mFirstChange = true;
    mPocketProgram.dataArray[0].timeMin = 0;

    Sensor proximitySensor = sensorManager.getDefaultSensor(getType());
    sensorManager.registerListener(this, proximitySensor, SensorManager.SENSOR_DELAY_NORMAL);

    mMaximumRange = proximitySensor.getMaximumRange();
    sAttached = true;
}
 
Example #4
Source File: GyroHelper.java    From libcommon with Apache License 2.0 7 votes vote down vote up
private void getOrientation(final float[] rotateMatrix, final float[] result) {

			switch (mRotation) {
			case Surface.ROTATION_0:
				SensorManager.getOrientation(rotateMatrix, result);
				return;
			case Surface.ROTATION_90:
				SensorManager.remapCoordinateSystem(
					rotateMatrix, SensorManager.AXIS_Y, SensorManager.AXIS_MINUS_X, outR);
				break;
			case Surface.ROTATION_180:
				SensorManager.remapCoordinateSystem(
					rotateMatrix, SensorManager.AXIS_Y, SensorManager.AXIS_MINUS_X, outR2);
				SensorManager.remapCoordinateSystem(
					outR2, SensorManager.AXIS_Y, SensorManager.AXIS_MINUS_X, outR);
				break;
			case Surface.ROTATION_270:
				SensorManager.remapCoordinateSystem(
					outR, SensorManager.AXIS_MINUS_Y, SensorManager.AXIS_MINUS_X, outR);
				break;
			}
			SensorManager.getOrientation(outR, result);
		}
 
Example #5
Source File: ReadingDetailsActivity.java    From Leisure with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Language
    mLang = Utils.getCurrentLanguage();
    if (mLang > -1) {
        Utils.changeLanguage(this, mLang);
    }


    //set Theme
    if(Settings.isNightMode){
        this.setTheme(R.style.NightTheme);
    }else{
        this.setTheme(R.style.DayTheme);
    }

    setContentView(R.layout.activity_reading_details);
    initData();

    mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);

}
 
Example #6
Source File: Engine.java    From tilt-game-android with MIT License 6 votes vote down vote up
/**
 * @return <code>true</code> when the sensor was successfully enabled, <code>false</code> otherwise.
 */
public boolean enableAccelerationSensor(final Context pContext, final IAccelerationListener pAccelerationListener, final AccelerationSensorOptions pAccelerationSensorOptions) {
	final SensorManager sensorManager = (SensorManager) pContext.getSystemService(Context.SENSOR_SERVICE);
	if (this.isSensorSupported(sensorManager, Sensor.TYPE_ACCELEROMETER)) {
		this.mAccelerationListener = pAccelerationListener;

		this.initDefaultDisplay(pContext);

		if (this.mAccelerationData == null) {
			this.mAccelerationData = new AccelerationData();
		}

		this.registerSelfAsSensorListener(sensorManager, Sensor.TYPE_ACCELEROMETER, pAccelerationSensorOptions.getSensorDelay());

		return true;
	} else {
		return false;
	}
}
 
Example #7
Source File: MainActivity.java    From Android-Example with Apache License 2.0 6 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ProximitySensor = (TextView)findViewById(R.id.proximitySensor);
    ProximityMax = (TextView)findViewById(R.id.proximityMax);
    ProximityReading = (TextView)findViewById(R.id.proximityReading);
    // Now in the SensorActivity we access the device sensor using SensorManager, an instance of this class is got by calling getSystemService(SENSOR_SERVICE) . We implement the class with theSensorEventListener interface to override its methods to do actions on sensor value change.
    mySensorManager = (SensorManager)getSystemService(
      Context.SENSOR_SERVICE);
    myProximitySensor = mySensorManager.getDefaultSensor(
      Sensor.TYPE_PROXIMITY);
    
    if (myProximitySensor == null){
     ProximitySensor.setText("No Proximity Sensor!"); 
    }else{
     ProximitySensor.setText(myProximitySensor.getName());
     ProximityMax.setText("Maximum Range: "
       + String.valueOf(myProximitySensor.getMaximumRange()));
     mySensorManager.registerListener(proximitySensorEventListener,
       myProximitySensor,
       SensorManager.SENSOR_DELAY_NORMAL);
    }
}
 
Example #8
Source File: SensorsDataAPI.java    From sa-sdk-android with Apache License 2.0 6 votes vote down vote up
@Override
public void enableTrackScreenOrientation(boolean enable) {
    try {
        if (enable) {
            if (mOrientationDetector == null) {
                mOrientationDetector = new SensorsDataScreenOrientationDetector(mContext, SensorManager.SENSOR_DELAY_NORMAL);
            }
            mOrientationDetector.enable();
        } else {
            if (mOrientationDetector != null) {
                mOrientationDetector.disable();
                mOrientationDetector = null;
            }
        }
    } catch (Exception e) {
        com.sensorsdata.analytics.android.sdk.SALog.printStackTrace(e);
    }
}
 
Example #9
Source File: SensorUtil.java    From Sensor-Disabler with MIT License 6 votes vote down vote up
public static Sensor getSensorFromUniqueSensorKey(Context context, String key) {
    String[] data = key.split(Pattern.quote(SENSOR_SEPARATOR)); //Regex, man. Regex.
    if (data.length >= 4) {
        try {
            String name = data[0];
            String vendor = data[1];
            int version = Integer.parseInt(data[2]);
            int type = Integer.parseInt(data[3]);
            SensorManager manager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
            for (Sensor sensor : manager.getSensorList(type)) {
                if (sensor.getName().equals(name)
                        && sensor.getVendor().equals(vendor)
                        && sensor.getVersion() == version) {
                    return sensor;
                }
            }
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("Unable to get unique sensor from key.");
        }
    } else {
        Log.e("SensorUtil", "Unable to parse \"" + key + "\" as Sensor data.");
    }
    return null;
}
 
Example #10
Source File: StreamActivity.java    From Pocket-Plays-for-Twitch with GNU General Public License v3.0 6 votes vote down vote up
protected void update(float[] vectors) {
	int worldAxisX = SensorManager.AXIS_X;
	int worldAxisZ = SensorManager.AXIS_Z;

	float[] rotationMatrix = new float[9];
	float[] adjustedRotationMatrix = new float[9];
	float[] orientation = new float[3];

	SensorManager.getRotationMatrixFromVector(rotationMatrix, vectors);
	SensorManager.remapCoordinateSystem(rotationMatrix, worldAxisX, worldAxisZ, adjustedRotationMatrix);
	SensorManager.getOrientation(adjustedRotationMatrix, orientation);

	float roll = orientation[2] * FROM_RADS_TO_DEGS;

	if (roll > -45 && roll < 45) {
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
		Log.d(LOG_TAG, "Requesting undefined");
	}
	Log.d(LOG_TAG, "Roll: " + roll);
}
 
Example #11
Source File: AmbientLightManager.java    From ProjectX with Apache License 2.0 6 votes vote down vote up
private void setTorch() {
    switch (mMode) {
        case MODE_AUTO:
            if (sensorManager != null) {
                sensorManager.registerListener(this,
                        sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT),
                        SensorManager.SENSOR_DELAY_NORMAL);
            }
            break;
        case MODE_OPEN:
            if (sensorManager != null) {
                sensorManager.unregisterListener(this);
            }
            if (mCallBack != null)
                mCallBack.onChange(true);
            break;
        case MODE_CLOSE:
            if (sensorManager != null) {
                sensorManager.unregisterListener(this);
            }
            if (mCallBack != null)
                mCallBack.onChange(false);
            break;
    }
}
 
Example #12
Source File: CompassActivity.java    From Wrox-ProfessionalAndroid-4E with Apache License 2.0 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_compass);
  mCompassView = findViewById(R.id.compassView);

  mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
  WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);

  Display display = wm.getDefaultDisplay();
  mScreenRotation = display.getRotation();

  mNewestValues = new float[] {0, 0, 0};

  Timer updateTimer = new Timer("compassUpdate");
  updateTimer.scheduleAtFixedRate(new TimerTask() {
    public void run() {
      updateGUI();
    }
  }, 0, 1000/60);
}
 
Example #13
Source File: ShakeDetectEventListener.java    From android-wear-gopro-remote with Apache License 2.0 6 votes vote down vote up
@Override
public void onSensorChanged(SensorEvent event) {
    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {

        long curTime = System.currentTimeMillis();
        // if a shake in last X seconds ignore.
        if (lastShake != 0 && (curTime - lastShake) < IGNORE_EVENTS_AFTER_SHAKE) return;

        float x = event.values[SensorManager.DATA_X];
        float y = event.values[SensorManager.DATA_Y];
        float z = event.values[SensorManager.DATA_Z];
        if (last_x != 0 && last_y != 0 && last_z != 0 && (last_x != x || last_y != y || last_z != z)) {
            DataPoint dp = new DataPoint(last_x-x, last_y-y, last_z-z, curTime);
            //Log.i("XYZ",Float.toString(dp.x)+"   "+Float.toString(dp.y)+"   "+Float.toString(dp.z)+"   ");
            dataPoints.add(dp);

            if ((curTime - lastUpdate) > SHAKE_CHECK_THRESHOLD) {
                lastUpdate = curTime;
                checkForShake();
            }
        }
        last_x = x;
        last_y = y;
        last_z = z;
    }
}
 
Example #14
Source File: AlternativeAccelHandler.java    From Alite with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onSensorChanged(SensorEvent event) {
	if (!getUpdates) {
		SensorManager manager = (SensorManager) game.getSystemService(Context.SENSOR_SERVICE);
		if (manager.getSensorList(Sensor.TYPE_ACCELEROMETER).size() > 0) {
			manager.unregisterListener(this);
		}			
		return;
	}
	switch (event.sensor.getType()) {
		case Sensor.TYPE_ACCELEROMETER:
			for (int i = 0; i < 3; i++) {
				accelValues[i] = event.values[i];
			}
			break;
	}

	float roll  = (float) Math.atan2(accelValues[0], accelValues[2]);
	float pitch = (float) Math.atan2(accelValues[1], accelValues[2]);

	accelValues[2] = -roll;
	accelValues[1] = -pitch;
	accelValues[0] = 0;
	adjustAccelOrientation(accelValues);
}
 
Example #15
Source File: AccelerometerCompassProvider.java    From tilt-game-android with MIT License 6 votes vote down vote up
@Override
public void onSensorChanged(SensorEvent event) {

    // we received a sensor event. it is a good practice to check
    // that we received the proper event
    if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
        magnitudeValues = event.values.clone();
    } else if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
        accelerometerValues = event.values.clone();
    }

    if (magnitudeValues != null && accelerometerValues != null) {
        float[] i = new float[16];

        // Fuse accelerometer with compass
        SensorManager.getRotationMatrix(currentOrientationRotationMatrix.matrix, i, accelerometerValues,
                magnitudeValues);
        // Transform rotation matrix to quaternion
        currentOrientationQuaternion.setRowMajor(currentOrientationRotationMatrix.matrix);
    }
}
 
Example #16
Source File: AeyriumSensorPlugin.java    From aeyrium-sensor with MIT License 6 votes vote down vote up
SensorEventListener createSensorEventListener(final EventChannel.EventSink events) {
  return new SensorEventListener() {
    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
      if (mLastAccuracy != accuracy) {
        mLastAccuracy = accuracy;
      }
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
      if (mLastAccuracy == SensorManager.SENSOR_STATUS_UNRELIABLE) {
        return;
      }

      updateOrientation(event.values, events);
    }
  };
}
 
Example #17
Source File: DataManager.java    From ibm-wearables-android-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * register the default sensor of specific type
 * @param type sensor id
 */
private void registerSensor(int type){
    Sensor defaultSensor = sensorManager.getDefaultSensor(type);

    //set normalization factor
    if (type == Sensor.TYPE_ACCELEROMETER){
        gestureDataHolder.allowSensorDataCollection(type);

        //normalize to range form -2 to 2
        gestureDataHolder.setNormalizationFactor(type, 2 / defaultSensor.getMaximumRange());
    }

    if (type == Sensor.TYPE_GYROSCOPE){
        gestureDataHolder.allowSensorDataCollection(type);

        //from rad to deg
        gestureDataHolder.setNormalizationFactor(type, 57.2958);
    }

    sensorManager.registerListener(this, defaultSensor, SensorManager.SENSOR_DELAY_GAME);
    //sensorManager.registerListener(this, defaultSensor, SensorManager.SENSOR_DELAY_FASTEST);
}
 
Example #18
Source File: SenseyTest.java    From sensey with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    Context context = RuntimeEnvironment.application.getApplicationContext();
    shadowSensorManager =
            Shadows.shadowOf((SensorManager) context.getSystemService(SENSOR_SERVICE));

    sensey = Sensey.getInstance();
    sensey.init(context);
}
 
Example #19
Source File: SensorActivity.java    From AndroidSchool with Apache License 2.0 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
    mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
}
 
Example #20
Source File: GestureLauncherService.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Registers for the camera lift trigger.
 */
private void registerCameraLiftTrigger(Resources resources) {
    if (mCameraLiftRegistered) {
        return;
    }
    SensorManager sensorManager = (SensorManager) mContext.getSystemService(
            Context.SENSOR_SERVICE);
    int cameraLiftTriggerId = resources.getInteger(
            com.android.internal.R.integer.config_cameraLiftTriggerSensorType);
    if (cameraLiftTriggerId != -1) {
        mCameraLiftRegistered = false;
        String sensorName = resources.getString(
            com.android.internal.R.string.config_cameraLiftTriggerSensorStringType);
        mCameraLiftTriggerSensor = sensorManager.getDefaultSensor(
                cameraLiftTriggerId,
                true /*wakeUp*/);

        // Compare the camera lift trigger string type to that in the resource file to make
        // sure we are registering the correct sensor. This is redundant check, it
        // makes the code more robust.
        if (mCameraLiftTriggerSensor != null) {
            if (sensorName.equals(mCameraLiftTriggerSensor.getStringType())) {
                mCameraLiftRegistered = sensorManager.requestTriggerSensor(mCameraLiftTriggerListener,
                        mCameraLiftTriggerSensor);
            } else {
                String message = String.format("Wrong configuration. Sensor type and sensor "
                        + "string type don't match: %s in resources, %s in the sensor.",
                        sensorName, mCameraLiftTriggerSensor.getStringType());
                throw new RuntimeException(message);
            }
        }
        if (DBG) Slog.d(TAG, "Camera lift trigger sensor registered: " + mCameraLiftRegistered);
    } else {
        if (DBG) Slog.d(TAG, "Camera lift trigger sensor is not specified.");
    }
}
 
Example #21
Source File: DataManager.java    From ibm-wearables-android-sdk with Apache License 2.0 5 votes vote down vote up
public DataManager(SensorManager sensorManager, DataSender dataSender){

        //sensorsHolder = new SensorsHolder(sensorManager);
        this.sensorManager = sensorManager;
        sensorManager.unregisterListener(this);
        this.dataSender = dataSender;
    }
 
Example #22
Source File: StabilizationService.java    From aosp_screen_stabilization with Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate()
{
	super.onCreate();

	settings = AppSettings.getAppSettings(getApplicationContext());

	sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
	accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION);

	registerReceiver(screenOnReceiver, new IntentFilter(Intent.ACTION_SCREEN_ON));
	registerReceiver(screenOffReceiver, new IntentFilter(Intent.ACTION_SCREEN_OFF));

	if (Utils.isScreenOn(this)) registerAccListener();
}
 
Example #23
Source File: ShakeDetector.java    From ShakeDetector with Apache License 2.0 5 votes vote down vote up
/**
 * Starts a previously created shake detector. If no detector has been created before, the method
 * won't create one and will return false.
 *
 * @return true if the shake detector has been started correctly, false otherwise.
 */
public static boolean start() {
    if (mSensorManager != null && mSensorEventListener != null) {
        return mSensorManager.registerListener(mSensorEventListener, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_GAME);
    }
    return false;
}
 
Example #24
Source File: StepCounter.java    From SensorsAndAi with MIT License 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate ( savedInstanceState );
    setContentView ( R.layout.activity_step_counter );
    tv_steps = (TextView) findViewById ( R.id.tv_steps );

    sensorManager = (SensorManager) getSystemService ( Context.SENSOR_SERVICE);
}
 
Example #25
Source File: SensorFilteredValuesActivity.java    From coursera-android with MIT License 5 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    mXValueView = findViewById(R.id.x_value_view);
    mYValueView = findViewById(R.id.y_value_view);
    mZValueView = findViewById(R.id.z_value_view);

    mXGravityView = findViewById(R.id.x_lowpass_view);
    mYGravityView = findViewById(R.id.y_lowpass_view);
    mZGravityView = findViewById(R.id.z_lowpass_view);

    mXAccelView = findViewById(R.id.x_highpass_view);
    mYAccelView = findViewById(R.id.y_highpass_view);
    mZAccelView = findViewById(R.id.z_highpass_view);

    // Get reference to SensorManager
    mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);

    if (null != mSensorManager) {
        // Get reference to Accelerometer
        mAccelerometer = mSensorManager
                .getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        if (null == mAccelerometer) finish();

        mLastUpdate = System.currentTimeMillis();
    }
}
 
Example #26
Source File: DeviceOrientation.java    From ARCore-Location with MIT License 5 votes vote down vote up
@Override
public void onSensorChanged(SensorEvent event) {

    // Get the device heading
    float degree = Math.round( event.values[0] );
    currentDegree = -degree;

    switch (event.sensor.getType()) {
        case Sensor.TYPE_MAGNETIC_FIELD:
            mags = event.values.clone();
            break;
        case Sensor.TYPE_ACCELEROMETER:
            accels = event.values.clone();
            break;
    }

    if (mags != null && accels != null) {
        gravity = new float[9];
        magnetic = new float[9];
        SensorManager.getRotationMatrix(gravity, magnetic, accels, mags);
        float[] outGravity = new float[9];
        SensorManager.remapCoordinateSystem(gravity, SensorManager.AXIS_X,SensorManager.AXIS_Z, outGravity);
        SensorManager.getOrientation(outGravity, values);

        azimuth = values[0] * 57.2957795f;
        pitch = values[1] * 57.2957795f;
        roll = values[2] * 57.2957795f;
        mags = null;
        accels = null;
    }
}
 
Example #27
Source File: DeviceMotionAndOrientation.java    From android-chromium with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private SensorManagerProxy getSensorManagerProxy() {
    if (mSensorManagerProxy != null) {
        return mSensorManagerProxy;
    }
    SensorManager sensorManager = (SensorManager)WeakContext.getSystemService(
            Context.SENSOR_SERVICE);
    if (sensorManager != null) {
        mSensorManagerProxy = new SensorManagerProxyImpl(sensorManager);
    }
    return mSensorManagerProxy;
}
 
Example #28
Source File: ShakeUpdateListener.java    From YiBo with Apache License 2.0 5 votes vote down vote up
@Override
public void onSensorChanged(SensorEvent event) {
	long currentTime = System.currentTimeMillis();
    if (currentTime - lastShakeTime < SHAKE_INTERVAL_TIME 
    	|| !sheJiaoMao.isRefreshOnShake()) {
    	return;
    }
 
    //获取加速度传感器的三个参数
    float x = event.values[SensorManager.DATA_X];
    float y = event.values[SensorManager.DATA_Y];
    float z = event.values[SensorManager.DATA_Z];
    //System.out.println("加速度: x->" + x + ", y->" + y + ", z->" + z);

	float tempDiffX = x - lastX;
	float tempDiffY = y - lastY;
    lastX = x;
    lastY = y;
    if (lastDiffX < 0 
    	&& lastDiffY < 0 
    	&& tempDiffX > SHAKE_UPDATE_ACCELERATION_X 
    	&& tempDiffY > SHAKE_UPDATE_ACCELERATION_Y) {
    	if (Logger.isDebug()) Log.v(TAG, "vibrateToUpdate: x->" + x + ", y->" + y + ", z->" + z);
    	vibrateToUpdate();
    }
    
    lastDiffX = tempDiffX;
    lastDiffY = tempDiffY;
}
 
Example #29
Source File: AccelerationData.java    From tilt-game-android with MIT License 5 votes vote down vote up
@Override
public void swapAxis(final float[] pValues) {
	final float x = pValues[SensorManager.DATA_X];
	final float y = pValues[SensorManager.DATA_Y];
	pValues[SensorManager.DATA_X] = x;
	pValues[SensorManager.DATA_Y] = y;
}
 
Example #30
Source File: OrientationManager.java    From CrossMobile with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static void register(MainActivity activity) {
    current = new OrientationEventListener(activity, SensorManager.SENSOR_DELAY_NORMAL) {
        int oldOrientation = -1;

        @Override
        public void onOrientationChanged(int angle) {
            int iosOrientation = -1;

            if (getInt(activity.getContentResolver(), ACCELEROMETER_ROTATION, 0) == 0) {
            } else if (angle < 0) {
            } else if (angle < DELTA || angle > (360 - DELTA))
                iosOrientation = UIDeviceOrientation.Portrait;
            else if (angle > (90 - DELTA) && angle < (90 + DELTA))
                iosOrientation = UIDeviceOrientation.LandscapeLeft;
            else if (angle > (180 - DELTA) && angle < (180 + DELTA))
                iosOrientation = UIDeviceOrientation.PortraitUpsideDown;
            else if (angle > (270 - DELTA) && angle < (270 + DELTA))
                iosOrientation = UIDeviceOrientation.LandscapeRight;

            if (iosOrientation < 0 || !GraphicsBridgeConstants.shouldAcceptOrientation(iosOrientation)) {
            } else if (oldOrientation != iosOrientation) {
                oldOrientation = iosOrientation;
                Native.graphics().setOrientation(iosOrientation);
                activity.onOrientationChanged(iosOrientation);
            }
        }
    };
    activity.getStateListener().register(new ActivityLifecycleListener() {
        @Override
        public void onPause() {
            current.disable();
        }

        @Override
        public void onResume() {
            if (current.canDetectOrientation())
                current.enable();
        }
    });
}