Java Code Examples for android.hardware.Sensor

The following are top voted examples for showing how to use android.hardware.Sensor. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: smart-asset-iot-android-demo   File: ShakeDetector.java   View source code 7 votes vote down vote up
/**
 * Starts listening for shakes on devices with appropriate hardware.
 *
 * @return true if the device supports shake detection.
 */
public boolean start(SensorManager sensorManager) {
    // Already started?
    if (accelerometer != null) {
        return true;
    }

    accelerometer = sensorManager.getDefaultSensor(
            Sensor.TYPE_ACCELEROMETER);

    // If this phone has an accelerometer, listen to it.
    if (accelerometer != null) {
        this.sensorManager = sensorManager;
        sensorManager.registerListener(this, accelerometer,
                SensorManager.SENSOR_DELAY_FASTEST);
    }
    return accelerometer != null;
}
 
Example 2
Project: homescreenarcade   File: GameActivity.java   View source code 7 votes vote down vote up
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    
    mySensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    myAccelerometer = mySensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    mySensorManager.registerListener(this, myAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);

    int level = getIntent().getIntExtra("level", 1);

    soundEngine = new com.homescreenarcade.mazeman.SoundEngine(this);
    gameEngine = new com.homescreenarcade.mazeman.GameEngine(this, soundEngine, level);
    
    Display display = getWindowManager().getDefaultDisplay();
    int width = display.getWidth();
    int height = display.getHeight();
    gameView = new com.homescreenarcade.mazeman.GameSurfaceView(this, gameEngine, width, height);

    setContentView(gameView);
   
    
}
 
Example 3
Project: GravityBox   File: ModLedControl.java   View source code 6 votes vote down vote up
private static void toggleActiveScreenFeature(boolean enable) {
    try {
        if (enable && mContext != null) {
            mPm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
            mKm = (KeyguardManager) mContext.getSystemService(Context.KEYGUARD_SERVICE);
            mSm = (SensorManager) mContext.getSystemService(Context.SENSOR_SERVICE);
            mProxSensor = mSm.getDefaultSensor(Sensor.TYPE_PROXIMITY);
        } else {
            mProxSensor = null;
            mSm = null;
            mPm = null;
            mKm = null;
        }
        if (DEBUG) log("Active screen feature: " + enable);
    } catch (Throwable t) {
        XposedBridge.log(t);
    }
}
 
Example 4
Project: Khonsu   File: SensorService.java   View source code 6 votes vote down vote up
@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    ssManager = (SensorManager)getSystemService(SENSOR_SERVICE);

    rotationSensor = ssManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);
    gravitySensor = ssManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    stepDetectSensor = ssManager.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR);
    magnetSensor = ssManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);

    // Check if sensors are available, if not close application
    if (rotationSensor == null) { hasRotationSensor = false; }
    if (gravitySensor == null || stepDetectSensor == null || magnetSensor == null) {
        sensorAvailable = false;
    }

    initListener();

    return START_NOT_STICKY;
}
 
Example 5
Project: Android-SteamVR-controller   File: AccelerometerCompassProvider.java   View source code 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) {
        System.arraycopy(event.values, 0, magnitudeValues, 0, magnitudeValues.length);
    } else if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
        System.arraycopy(event.values, 0, accelerometerValues, 0, accelerometerValues.length);
    }

    if (magnitudeValues != null && accelerometerValues != null) {
        // Fuse accelerometer with compass
        SensorManager.getRotationMatrix(currentOrientationRotationMatrix.matrix, inclinationValues, accelerometerValues,
                magnitudeValues);
        // Transform rotation matrix to quaternion
        currentOrientationQuaternion.setRowMajor(currentOrientationRotationMatrix.matrix);
    }
}
 
Example 6
Project: MapDemo   File: MyOrientationListener.java   View source code 6 votes vote down vote up
@SuppressWarnings(
{ "deprecation" })
@Override
public void onSensorChanged(SensorEvent event)
{
	if (event.sensor.getType() == Sensor.TYPE_ORIENTATION)
	{
		float x = event.values[SensorManager.DATA_X];

		if (Math.abs(x - lastX) > 1.0)
		{
			if (mOnOrientationListener != null)
			{
				mOnOrientationListener.onOrientationChanged(x);
			}
		}

		lastX = x;

	}
}
 
Example 7
Project: SmART-Form   File: CameraActivity.java   View source code 6 votes vote down vote up
@Override
public void onSensorChanged(SensorEvent event) {
    if(event.sensor.getType() == Sensor.TYPE_LIGHT){
        mLightReading = event.values[0];
        if(mLightReading<20) {
            text_lightreading.setText("LIGHT: " + mLightReading + "; " + "Low light condition!");
        } else {
            text_lightreading.setText("LIGHT: " + mLightReading);
        }
    }
}
 
Example 8
Project: QuranAndroid   File: TranslationReadActivity.java   View source code 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.activity_translation_read);
    db = new DatabaseHandler(this);
    sm = (SensorManager) getSystemService(SENSOR_SERVICE);
    proxSensor = sm.getDefaultSensor(Sensor.TYPE_PROXIMITY);
    lightSensor = sm.getDefaultSensor(Sensor.TYPE_LIGHT);
    sm.registerListener(this,proxSensor,SensorManager.SENSOR_DELAY_NORMAL);
    //toolbar object
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    //init translation read activity
    init();
}
 
Example 9
Project: robo-car   File: MagnetoMeter.java   View source code 6 votes vote down vote up
@Override
public void turnOn(Context context) {
    mSensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
    mSensorManager.registerDynamicSensorCallback(new SensorManager.DynamicSensorCallback() {
        @Override
        public void onDynamicSensorConnected(Sensor sensor) {
            if (sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
                mSensorManager.registerListener(mListener, sensor, SensorManager.SENSOR_DELAY_NORMAL);
            }
        }
    });

    try {
        mSensorDriver = new HMC5883LSensorDriver(BoardDefaults.getI2CPortForMagnetometer());
        mSensorDriver.registerMagmetormeterSensor();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 10
Project: Zxing-Custom   File: AmbientLightManager.java   View source code 5 votes vote down vote up
public void start(CameraManager cameraManager) {
  this.cameraManager = cameraManager;
  SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
  if (FrontLightMode.readPref(sharedPrefs) == FrontLightMode.AUTO) {
    SensorManager sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
    lightSensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
    if (lightSensor != null) {
      sensorManager.registerListener(this, lightSensor, SensorManager.SENSOR_DELAY_NORMAL);
    }
  }
}
 
Example 11
Project: labtablet   File: FieldModeActivity.java   View source code 5 votes vote down vote up
@Override
protected void onResume() {
    super.onResume();
    Log.e("fieldMode", "resume");

    sensorManager.registerListener(this,
            sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT),
            SensorManager.SENSOR_DELAY_NORMAL);

    sensorManager.registerListener(this,
            sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD),
            SensorManager.SENSOR_DELAY_NORMAL);

    registerBatInforReceiver();
}
 
Example 12
Project: AndroidSensors   File: IMUSensorGatherer.java   View source code 5 votes vote down vote up
private SensorEventListener initializeSensorEventListenerFor(final FlowableEmitter<SensorRecord> subscriber) {
    return new SensorEventListener() {

        @Override
        public void onSensorChanged(SensorEvent event) {
            subscriber.onNext(createSensorRecordFrom(event));
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {}
    };
}
 
Example 13
Project: Android-Real-Time-Chart   File: MainActivity.java   View source code 5 votes vote down vote up
@Override
protected void onResume() {
    super.onResume();
    sensorManager.registerListener(this,
            sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
            SensorManager.SENSOR_DELAY_NORMAL);
}
 
Example 14
Project: Ftc2018RelicRecovery   File: FtcAndroidGyro.java   View source code 5 votes vote down vote up
/**
 * Constructor: Creates an instance of the object.
 *
 * @param instanceName specifies the instance name.
 * @param filters specifies an array of filters to use for filtering sensor noise, one for each axis. Since we
 *                have 3 axes, the array should have 3 elements. If no filters are used, it can be set to null.
 */
public FtcAndroidGyro(String instanceName, TrcFilter[] filters)
{
    super(instanceName, 3, GYRO_HAS_X_AXIS | GYRO_HAS_Y_AXIS | GYRO_HAS_Z_AXIS | GYRO_INTEGRATE, filters);

    if (debugEnabled)
    {
        dbgTrace = new TrcDbgTrace(moduleName + "." + instanceName, tracingEnabled, traceLevel, msgLevel);
    }

    sensor = new FtcAndroidSensor(instanceName, Sensor.TYPE_GYROSCOPE, 3);
}
 
Example 15
Project: androidthings   File: MainActivity.java   View source code 5 votes vote down vote up
@Override
public void onDynamicSensorConnected(Sensor sensor) {
    Log.i(TAG, sensor.getName() + " has been connected");

    // Begin listening for sensor readings
    sensorManager.registerListener(MainActivity.this, sensor,
            SensorManager.SENSOR_DELAY_NORMAL);
}
 
Example 16
Project: 420Game   File: HostLobbyActivity.java   View source code 5 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.CUPCAKE)
@Override
public void onSensorChanged(SensorEvent event) {
    // when pressure value is changed, this method will be called.
    float pressure_value = 0.0f;

    // if you use this listener as listener of only one sensor (ex, Pressure), then you don't need to check sensor type.
    if( Sensor.TYPE_PRESSURE == event.sensor.getType() ) {
        pressure_value = event.values[0];
        //mAddressLabel = (TextView)findViewById(R.id.hostlobby_address);
       // mAddressLabel.setText(String.valueOf(pressure_value));

        mCurrentPressure = pressure_value;
    }
}
 
Example 17
Project: 2017.2-codigo   File: SensorListActivity.java   View source code 5 votes vote down vote up
private boolean isXYZ(Sensor s) {
    switch (s.getType()) {
        case Sensor.TYPE_ACCELEROMETER:
        case Sensor.TYPE_GRAVITY:
        case Sensor.TYPE_GYROSCOPE:
        case Sensor.TYPE_LINEAR_ACCELERATION:
        case Sensor.TYPE_MAGNETIC_FIELD:
        case Sensor.TYPE_ROTATION_VECTOR:
            return true;
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
        if (s.getType() == Sensor.TYPE_GAME_ROTATION_VECTOR
                || s.getType() == Sensor.TYPE_GYROSCOPE_UNCALIBRATED
                || s.getType() == Sensor.TYPE_MAGNETIC_FIELD_UNCALIBRATED) {
            return true;
        }
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        if (s.getType() == Sensor.TYPE_GEOMAGNETIC_ROTATION_VECTOR) {
            return true;
        }
    }

    return false;
}
 
Example 18
Project: proto-collecte   File: CameraActivity.java   View source code 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_camera);
    mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
    accelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    magnetometer = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
    txt = (TextView) findViewById(R.id.label_hello);
}
 
Example 19
Project: 420Game   File: JoinLobbyActivity.java   View source code 5 votes vote down vote up
@Override
public void onSensorChanged(SensorEvent event) {
    // when pressure value is changed, this method will be called.
    float pressure_value = 0.0f;

    // if you use this listener as listener of only one sensor (ex, Pressure), then you don't need to check sensor type.
    if( Sensor.TYPE_PRESSURE == event.sensor.getType() ) {
        pressure_value = event.values[0];
        //mAddressLabel = (TextView)findViewById(R.id.hostlobby_address);
        // mAddressLabel.setText(String.valueOf(pressure_value));

        mCurrentPressure = pressure_value;
    }
}
 
Example 20
Project: Android-SteamVR-controller   File: ImprovedOrientationSensor1Provider.java   View source code 5 votes vote down vote up
/**
 * Initialises a new ImprovedOrientationSensor1Provider
 * 
 * @param sensorManager The android sensor manager
 */
public ImprovedOrientationSensor1Provider(SensorManager sensorManager, int sensorRefreshSpeed) {
    super(sensorManager, sensorRefreshSpeed);

    //Add the gyroscope and rotation Vector
    sensorList.add(sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE));
    sensorList.add(sensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR));
}
 
Example 21
Project: AppRTC-Android   File: AppRTCProximitySensor.java   View source code 5 votes vote down vote up
@Override
public final void onAccuracyChanged(Sensor sensor, int accuracy) {
  threadChecker.checkIsOnValidThread();
  AppRTCUtils.assertIsTrue(sensor.getType() == Sensor.TYPE_PROXIMITY);
  if (accuracy == SensorManager.SENSOR_STATUS_UNRELIABLE) {
    Log.e(TAG, "The values returned by this sensor cannot be trusted");
  }
}
 
Example 22
Project: ThunderMusic   File: MediaLockscreenActivity.java   View source code 5 votes vote down vote up
/**
 * Called when the activity is first created.
 */
@Override
public void onCreate(Bundle icicle) {
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2) {
        Window w = getWindow(); // in Activity's onCreate() for instance
        w.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION,
                WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        w.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
                WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
    }
    super.onCreate(icicle);
    setVolumeControlStream(AudioManager.STREAM_MUSIC);
    activity = this;
    WindowManager.LayoutParams lp = getWindow().getAttributes();
    previousScreenBrightness = lp.screenBrightness;

    mSettings = PreferenceManager.getDefaultSharedPreferences(this);
    mSettings.registerOnSharedPreferenceChangeListener(this);
    if (mSettings.getBoolean("use_as_lock", false)) {
        getWindow().addFlags(
                WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
    } else {
        getWindow().clearFlags(
                WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
    }
    audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

    if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean(
            PreferencesActivity.KEY_MUSMART_LOCK, true)) {
        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        mProximity = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
    }

    initViews();
}
 
Example 23
Project: Android-Wear-Projects   File: WearStepService.java   View source code 5 votes vote down vote up
@Override
    public void onSensorChanged(SensorEvent event) {
        if (event.sensor.getType() == Sensor.TYPE_STEP_COUNTER)
            StepsTaken.updateSteps(event.values.length);
        Log.d(TAG, "onSensorChanged: steps count is" + event.values.length);
//        sendToPhone();
        sendData();
        updateNotification();
    }
 
Example 24
Project: VRPhoto   File: MainActivity.java   View source code 5 votes vote down vote up
private void initView(){
    getSupportActionBar().hide();
    img = (ImageView)findViewById(R.id.img);

    //展示最中间的一张
    int lenght = imgArray.length;
    int i = lenght%2==0 ? lenght/2-1 : lenght/2;
    img.setImageResource(imgArray[imgArray.length/2 - 1]);
    curFrame = i;

    mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);
}
 
Example 25
Project: PDR   File: StepDetector.java   View source code 5 votes vote down vote up
public void onResume() {
	sensorManager.registerListener(this,
			sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
			SensorManager.SENSOR_DELAY_FASTEST);

	sensorManager.registerListener(this,
			sensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION),
			SensorManager.SENSOR_DELAY_FASTEST);
	
	sensorManager.registerListener(this, 
			sensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY),
			SensorManager.SENSOR_DELAY_FASTEST);
}
 
Example 26
Project: CustomAndroidOneSheeld   File: GyroscopeShield.java   View source code 5 votes vote down vote up
@Override
public ControllerParent<GyroscopeShield> invalidate(
        com.integreight.onesheeld.shields.ControllerParent.SelectionAction selectionAction,
        boolean isToastable) {
    this.selectionAction = selectionAction;
    mSensorManager = (SensorManager) getApplication().getSystemService(
            Context.SENSOR_SERVICE);
    mGyroscope = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
    registerSensorListener(isToastable);
    return super.invalidate(selectionAction, isToastable);
}
 
Example 27
Project: PhoneFoneFun   File: MainActivity.java   View source code 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ActionBar b = getActionBar();
    if (b!=null) b.hide();

    display = (TextView) findViewById(R.id.display);
    switchPhone = (Switch) findViewById(R.id.switchPhone);

    hellos = getResources().getStringArray(R.array.hello);
    byes = getResources().getStringArray(R.array.bye);
    convos = getResources().getStringArray(R.array.convo);

    mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);

    mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);


    findViewById(R.id.about_link).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent about = new Intent(MainActivity.this, AboutActivity.class);
            startActivity(about);
        }
    });


}
 
Example 28
Project: HttpProxyInjection   File: BaseActivity.java   View source code 5 votes vote down vote up
@Override
protected void onStart() {
    super.onStart();
    //获取 SensorManager 负责管理传感器
    mSensorManager = ((SensorManager) getSystemService(SENSOR_SERVICE));
    if (mSensorManager != null) {
        //获取加速度传感器
        mAccelerometerSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        if (mAccelerometerSensor != null) {
            mSensorManager.registerListener(this, mAccelerometerSensor, SensorManager.SENSOR_DELAY_NORMAL);
        }
    }
}
 
Example 29
Project: CustomAndroidOneSheeld   File: OrientationShield.java   View source code 5 votes vote down vote up
@SuppressWarnings("deprecation")
@Override
public ControllerParent<OrientationShield> invalidate(
        com.integreight.onesheeld.shields.ControllerParent.SelectionAction selectionAction,
        boolean isToastable) {
    this.selectionAction = selectionAction;
    mSensorManager = (SensorManager) getApplication().getSystemService(
            Context.SENSOR_SERVICE);
    mOrientation = mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
    registerSensorListener(isToastable);
    return super.invalidate(selectionAction, isToastable);
}
 
Example 30
Project: nirbhaya   File: PhoneLocatorService.java   View source code 5 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();
    //setting up the broadcast

    am = (AudioManager)(getApplicationContext().getSystemService(Context.AUDIO_SERVICE));
    mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.siren);
    mediaPlayer.setLooping(true);

    sensorManager = (SensorManager)getSystemService(getApplicationContext().SENSOR_SERVICE);
    sensorAccelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

    sensorManager.registerListener(this, sensorAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);

    mBroadcastReceiver = new SMSBroadcastReceiver();
    IntentFilter filter = new IntentFilter();
    filter.addAction("android.provider.Telephony.SMS_RECEIVED");
    registerReceiver(mBroadcastReceiver, filter);


    IntentFilter newFilter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
    registerReceiver(mReceiver, newFilter);


    PowerManager manager =
            (PowerManager) getSystemService(Context.POWER_SERVICE);
    mWakeLock = manager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, PhoneLocatorService.class.getName());

    // Create a notification area notification so the user
    // can get back to the PhoneLocator Service and Close It

    final Intent notificationIntent = new Intent(getApplicationContext(),
            NirbhayaActivity.class);
    final PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
            notificationIntent, 0);

    final Notification notification = new Notification.Builder(
            getApplicationContext())
            .setSmallIcon(R.drawable.ic_launcher)
            .setOngoing(true).setContentTitle("Nirbhaya")
            .setContentText("Click to Access Nirbhaya Service")
            .setContentIntent(pendingIntent).build();

    // Put this Service in a foreground state, so it won't
    // readily be killed by the system
    startForeground(NOTIFICATION_ID, notification);

    firstTimeAlert = false;
    mLocationSendServiceIntent = new Intent(NirbhayaActivity.getMainApp(), LocationSendService.class);
}
 
Example 31
Project: AndroidPedometer   File: stepCore.java   View source code 5 votes vote down vote up
public void onSensorChanged(SensorEvent event) {
    Sensor sensor = event.sensor;
    synchronized (this) {
        if (sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
            calc_step(event);
        }
    }
}
 
Example 32
Project: GravityBox   File: CallFeatures.java   View source code 5 votes vote down vote up
private void attachSensorListener() {
    if (mSensorManager == null || 
            mSensorListenerAttached ||
            mFlipAction == GravityBoxSettings.PHONE_FLIP_ACTION_NONE) return;

    mPhoneSensorEventListener.reset();
    mSensorManager.registerListener(mPhoneSensorEventListener, 
            mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), 
            SensorManager.SENSOR_DELAY_NORMAL);
    mSensorListenerAttached = true;

    if (DEBUG) log("Sensor listener attached");
}
 
Example 33
Project: renderscript_examples   File: MainActivity.java   View source code 5 votes vote down vote up
@Override
public void onSensorChanged(SensorEvent event) {
    Sensor evtSensor = event.sensor;

    if(evtSensor.getType()==Sensor.TYPE_ACCELEROMETER)
    {
        double x = event.values[0];
        double y = event.values[1];

        double maxValue = Math.sqrt(x*x+y*y);

        double xDiv = x/maxValue;
        double yDiv = y/maxValue;

        // Calculates new falling angle
        double angle = Math.atan(yDiv/xDiv) + (x < 0 ? Math.PI : 0);

        float accY = accG*(float)Math.sin(angle);
        float accX = -accG*(float)Math.cos(angle);

        // Push new angle data to RS
        if(scriptMain != null) {
            scriptMain.set_accY((float) accY);
            scriptMain.set_accX((float) accX);
        }

    }
}
 
Example 34
Project: phonk   File: PLightIntensity.java   View source code 5 votes vote down vote up
@ProtoMethod(description = "Start the light sensor. Returns the intensity. The value per device might vary", example = "")
@ProtoMethodParam(params = {"function(intensity)"})
public void start() {
    super.start();

    mListener = new SensorEventListener() {

        @Override
        public void onSensorChanged(SensorEvent event) {
            ReturnObject r = new ReturnObject();
            r.put("intensity", event.values[0]);
            mCallbackLightChange.event(r);
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {
            switch (accuracy) {
                case SensorManager.SENSOR_STATUS_UNRELIABLE:
                    break;
                case SensorManager.SENSOR_STATUS_ACCURACY_LOW:
                    break;
                case SensorManager.SENSOR_STATUS_ACCURACY_MEDIUM:
                    break;
                case SensorManager.SENSOR_STATUS_ACCURACY_HIGH:
                    break;
            }
        }

    };

    isEnabled = mSensormanager.registerListener(mListener, sensor, speed);
}
 
Example 35
Project: RandomLayout   File: ShakeListener.java   View source code 5 votes vote down vote up
/** 界面可见时候才监听摇晃 */
public void resume() {
	mSensorMgr = (SensorManager) mContext.getSystemService(Context.SENSOR_SERVICE);
	if (mSensorMgr == null) {
		throw new UnsupportedOperationException("Sensors not supported");
	}

	boolean supported = mSensorMgr.registerListener(this, mSensorMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
			SensorManager.SENSOR_DELAY_UI);
	if (!supported) {
		mSensorMgr.unregisterListener(this);
		return;
	}
}
 
Example 36
Project: RandomLayout   File: ShakeListener.java   View source code 5 votes vote down vote up
@Override
public void onSensorChanged(SensorEvent event) {

	System.out.println("x:" + event.values[SensorManager.DATA_X] + "  y:" + event.values[SensorManager.DATA_Y]
			+ "  z:" + event.values[SensorManager.DATA_Z]);

	if (event.sensor.getType() != Sensor.TYPE_ACCELEROMETER) {
		return;
	}

	long now = System.currentTimeMillis();

	if ((now - mLastForce) > SHAKE_TIMEOUT) {
		mShakeCount = 0;
	}

	if ((now - mLastTime) > TIME_THRESHOLD) {
		long diff = now - mLastTime;
		// 把X,Y,Z方向的距离除以时间,得出速度
		float speed = Math.abs(event.values[SensorManager.DATA_X] + event.values[SensorManager.DATA_Y]
				+ event.values[SensorManager.DATA_Z] - mLastX - mLastY - mLastZ)
				/ diff * 10000;
		if (speed > FORCE_THRESHOLD) {// 如果速度大于某个值
			// 先把摇晃的次数+1,再判断是否超过了要换的次数,并且间隙大于特定的值
			if ((++mShakeCount >= SHAKE_COUNT) && (now - mLastShake > SHAKE_DURATION)) {
				mLastShake = now;
				mShakeCount = 0;
				if (mShakeListener != null) {// 回调我们的listener
					mShakeListener.onShake();
				}
			}
			mLastForce = now;
		}
		mLastTime = now;
		mLastX = event.values[SensorManager.DATA_X];
		mLastY = event.values[SensorManager.DATA_Y];
		mLastZ = event.values[SensorManager.DATA_Z];
	}
}
 
Example 37
Project: renderscript_examples   File: MainActivity.java   View source code 5 votes vote down vote up
private void example() {
    // Prevent window dimming
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

    // Initialize accelerometer
    sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
    sensorAccelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    sensorManager.registerListener(this, sensorAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);

    // Initializes RenderScript context
    initRenderScript();

    // Here we get our TextureView, and apply a hack (setScaleX) to enable smoothing of the
    // final output image
    SurfaceView surfaceView = (SurfaceView) findViewById(R.id.surfaceView);

    // Sets surface callback, to understand when the surface will be available
    surfaceView.getHolder().addCallback(mSurfaceViewCallback);

    surfaceView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // After touching the surface, application will end.
            if (rsLoop != null)
                rsLoop.interrupt();

            System.exit(0);
        }
    });
}
 
Example 38
Project: haven   File: BumpMonitor.java   View source code 5 votes vote down vote up
@Override
public void onTrigger(TriggerEvent event) {
    Log.i("BumpMonitor", "Sensor triggered");
    //value[0] = 1.0 when the sensor triggers. 1.0 is the only allowed value.
    long curTime = System.currentTimeMillis();
    // only allow one update every 100ms.
    if (event.sensor.getType() == Sensor.TYPE_SIGNIFICANT_MOTION) {
        if ((curTime - lastUpdate) > CHECK_INTERVAL) {
            lastUpdate = curTime;

            /*
             * Send Alert
             */
            Message message = new Message();
            message.what = EventTrigger.BUMP;

            try {
                if (serviceMessenger != null) {
                    serviceMessenger.send(message);
                }
            } catch (RemoteException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    //re-register the listener (it finishes after each event)
    boolean registered = sensorMgr.requestTriggerSensor(sensorListener, bumpSensor);
    Log.i("BumpMonitor", "Significant motion sensor re-registered: "+registered);

}
 
Example 39
Project: AndroidPedometer   File: HardwarePedometerUtil.java   View source code 5 votes vote down vote up
/**
 * 是否支持step counter记步传感器
 * 方式:1、有TYPE_STEP_COUNTER;2、版本为4.4(19)以上
 */
public static boolean supportsHardwareStepCounter(Context context) {
    SensorManager mSensorManager = (SensorManager) context.getSystemService(context.SENSOR_SERVICE);
    Log.i("lipy", "sensor.getType() mStepCount = \n " + mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER)
            + "\n mStepDetector = " + mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR)
            + "\n mAccelerometer = " + mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER));

    return (Build.VERSION.SDK_INT >= 19) && (areSensorsPresent(context));
}
 
Example 40
Project: RoadLab-Pro   File: GravityAccelerometerDetector.java   View source code 5 votes vote down vote up
public boolean start() {
    if (eventsEnabled) {
        return false;
    }
    Log.d(TAG, "start");
    if (sensorManager != null) {
        testLastAccelerometerDataEntry = new AccelerometerDataEntry();
        testPreviousAccelerometerDataEntry = new AccelerometerDataEntry();
        gravityAvailable = checkSensorAvailability(sensorManager, Sensor.TYPE_GRAVITY);
        linearAccelerationAvailable = checkSensorAvailability(sensorManager, Sensor.TYPE_LINEAR_ACCELERATION);

        if (gravityAvailable) {
            sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY), SensorManager.SENSOR_DELAY_NORMAL);
        } else {
            softGravitySensor = new GravitySoftwareSensor();
        }
        if (linearAccelerationAvailable) {
            sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION), SensorManager.SENSOR_DELAY_NORMAL);
        } else {
            softGravitySensor = new GravitySoftwareSensor();
        }
        sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
        eventsEnabled = true;
        sendOnShakeDetectionBroadcast(false);
        return true;
    }
    return false;
}