Java 类android.hardware.Sensor 实例源码

项目:smart-asset-iot-android-demo    文件:ShakeDetector.java   
/**
 * 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;
}
项目:GravityBox    文件:ModLedControl.java   
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);
    }
}
项目:homescreenarcade    文件:GameActivity.java   
/** 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);


}
项目:Khonsu    文件:SensorService.java   
@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;
}
项目:Android-SteamVR-controller    文件:AccelerometerCompassProvider.java   
@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);
    }
}
项目:MapDemo    文件:MyOrientationListener.java   
@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;

    }
}
项目:QuranAndroid    文件:TranslationReadActivity.java   
@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();
}
项目:robo-car    文件:MagnetoMeter.java   
@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();
    }
}
项目:Zxing-Custom    文件:AmbientLightManager.java   
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);
    }
  }
}
项目:labtablet    文件:FieldModeActivity.java   
@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();
}
项目:AndroidSensors    文件:IMUSensorGatherer.java   
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) {}
    };
}
项目:Android-Real-Time-Chart    文件:MainActivity.java   
@Override
protected void onResume() {
    super.onResume();
    sensorManager.registerListener(this,
            sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
            SensorManager.SENSOR_DELAY_NORMAL);
}
项目:Ftc2018RelicRecovery    文件:FtcAndroidGyro.java   
/**
 * 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);
}
项目:androidthings    文件:MainActivity.java   
@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);
}
项目:420Game    文件:HostLobbyActivity.java   
@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;
    }
}
项目:2017.2-codigo    文件:SensorListActivity.java   
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;
}
项目:proto-collecte    文件:CameraActivity.java   
@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);
}
项目:420Game    文件:JoinLobbyActivity.java   
@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;
    }
}
项目:Android-SteamVR-controller    文件:ImprovedOrientationSensor1Provider.java   
/**
 * 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));
}
项目:AppRTC-Android    文件:AppRTCProximitySensor.java   
@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");
  }
}
项目:ThunderMusic    文件:MediaLockscreenActivity.java   
/**
 * 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();
}
项目:Android-Wear-Projects    文件:WearStepService.java   
@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();
    }
项目:VRPhoto    文件:MainActivity.java   
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);
}
项目:PDR    文件:StepDetector.java   
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);
}
项目:CustomAndroidOneSheeld    文件:GyroscopeShield.java   
@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);
}
项目:SmART-Form    文件:CameraActivity.java   
@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);
        }
    }
}
项目:PhoneFoneFun    文件:MainActivity.java   
@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);
        }
    });


}
项目:HttpProxyInjection    文件:BaseActivity.java   
@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);
        }
    }
}
项目:CustomAndroidOneSheeld    文件:OrientationShield.java   
@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);
}
项目:nirbhaya    文件:PhoneLocatorService.java   
@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);
}
项目:AndroidPedometer    文件:stepCore.java   
public void onSensorChanged(SensorEvent event) {
    Sensor sensor = event.sensor;
    synchronized (this) {
        if (sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
            calc_step(event);
        }
    }
}
项目:GravityBox    文件:CallFeatures.java   
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");
}
项目:renderscript_examples    文件:MainActivity.java   
@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);
        }

    }
}
项目:phonk    文件:PLightIntensity.java   
@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);
}
项目:RandomLayout    文件:ShakeListener.java   
/** 界面可见时候才监听摇晃 */
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;
    }
}
项目:RandomLayout    文件:ShakeListener.java   
@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];
    }
}
项目:renderscript_examples    文件:MainActivity.java   
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);
        }
    });
}
项目:haven    文件:BumpMonitor.java   
@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);

}
项目:AndroidPedometer    文件:HardwarePedometerUtil.java   
/**
 * 是否支持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));
}
项目:RoadLab-Pro    文件:GravityAccelerometerDetector.java   
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;
}