Example usage for android.content Context SENSOR_SERVICE

List of usage examples for android.content Context SENSOR_SERVICE

Introduction

In this page you can find the example usage for android.content Context SENSOR_SERVICE.

Prototype

String SENSOR_SERVICE

To view the source code for android.content Context SENSOR_SERVICE.

Click Source Link

Document

Use with #getSystemService(String) to retrieve a android.hardware.SensorManager for accessing sensors.

Usage

From source file:edu.cens.loci.sensors.AccelerometerHandler.java

public void start() {

    if (mIsOn)/*from ww  w  .jav a2  s.c om*/
        return;

    mCpuLock = cpu().newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "AccelerometerHandler.CpuLock");
    mCpuLock.setReferenceCounted(false);

    mIsOn = true;

    if (mDuration > 0) {
        //mCpuLock.acquire();
        mOnTimer = new Timer("sensorTurnOnTimer");
        mOffTimer = new Timer("sensorTurnOffTimer");

        mOnTimer.scheduleAtFixedRate(new TimerTask() {
            public void run() {
                mSensorService = (SensorManager) mCxt.getSystemService(Context.SENSOR_SERVICE);

                synchronized (this) {
                    MyLog.i(LociConfig.D.ACC, TAG, "[ACC] ON ");
                    mCpuLock.acquire();
                    mSensorOn = true;
                    mSensorService.registerListener(sInstance,
                            mSensorService.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), mRate);
                }
            }
        }, 0, mPeriod);

        mOffTimer.scheduleAtFixedRate(new TimerTask() {
            public void run() {

                synchronized (this) {
                    MyLog.i(LociConfig.D.ACC, TAG, "[ACC] OFF ");
                    mSensorOn = false;
                    if (mCpuLock.isHeld())
                        mCpuLock.release();
                    mSensorService.unregisterListener(sInstance,
                            mSensorService.getDefaultSensor(Sensor.TYPE_ACCELEROMETER));
                }
                // time to turn off sensor -- somehow send data

                //mXArr.reset();
                //mYArr.reset();
                //mZArr.reset();
                long time = Calendar.getInstance().getTime().getTime();
                float magVar = getMagnitudeVariance();
                //LociMobileManagerService.getInstance().eventAccelerometerResult(Calendar.getInstance().getTime().getTime(), magVar);

                mListener.onAccelerometerChanged(time, magVar);

                //if (LociMobileManagerService.getInstance().isMDOn()) 
                //   LociMobileManagerService.getInstance().getSystemDb().updatePowerRow(SystemLogDbAdapter.SENSOR_ACC, System.currentTimeMillis());
            }
        }, mDuration, mPeriod);

    } else {

        mCpuLock.acquire();
        mSensorService = (SensorManager) mCxt.getSystemService(Context.SENSOR_SERVICE);
        mSensorService.registerListener(this, mSensorService.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
                mRate);

        mReportTimer = new Timer("SensorReportTimer");
        mReportTimer.scheduleAtFixedRate(new TimerTask() {
            public void run() {
                // send data
                long time = Calendar.getInstance().getTime().getTime();
                float magVar = getMagnitudeVariance();
                mListener.onAccelerometerChanged(time, magVar);
                //LociMobileManagerService.getInstance().eventAccelerometerResult(Calendar.getInstance().getTime().getTime(), magVar);
                //if (LociMobileManagerService.getInstance().isMDOn()) 
                //   LociMobileManagerService.getInstance().getSystemDb().updatePowerRow(SystemLogDbAdapter.SENSOR_ACC, System.currentTimeMillis());
            }
        }, 0, mDuration);
    }

    //LociMobileManagerService.getInstance().getSystemDb().addPowerRow(SystemLogDbAdapter.SENSOR_ACC, System.currentTimeMillis());
    startChkTimer();
}

From source file:de.uni_weimar.benike.misex3.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // register for accelerometer events:
    mSensorManager = (SensorManager) getApplicationContext().getSystemService(Context.SENSOR_SERVICE);
    for (Sensor sensor : mSensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER)) {
        if (sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
            mAccelerometerSensor = sensor;
        }//w ww. j  a  v a2s  . c  om
    }

    // if we can't access the accelerometer sensor then exit:
    if (mAccelerometerSensor == null) {
        Log.e(TAG, "Failed to attach to Accelerator Sensor.");
        Toast.makeText(this, "Error! Failed to create accelerometer sensor!", Toast.LENGTH_LONG).show();
        cleanup();
    }

    mSensorManager.registerListener(this, mAccelerometerSensor, SensorManager.SENSOR_DELAY_UI);

    // setup the Accelerometer History plot:
    mAccelerometerPlot = (XYPlot) findViewById(R.id.accelerometerPlot);
    mFftPlot = (XYPlot) findViewById(R.id.fftPlot);

    mAccelerometerPlot.setRangeBoundaries(-25, 25, BoundaryMode.FIXED);
    mAccelerometerPlot.setDomainBoundaries(0, mWindowSize - 1, BoundaryMode.FIXED);

    mFftPlot.setRangeBoundaries(0, 250, BoundaryMode.FIXED);
    mFftPlot.setDomainBoundaries(0, mWindowSize / 2, BoundaryMode.AUTO);
    mFftPlot.setDomainStep(XYStepMode.SUBDIVIDE, 10);
    //mFftPlot.setRangeStep(XYStepMode.INCREMENT_BY_VAL, 50);

    mAccelerometerXSeries = new SimpleXYSeries("X");
    mAccelerometerXSeries.useImplicitXVals();
    mAccelerometerYSeries = new SimpleXYSeries("Y");
    mAccelerometerYSeries.useImplicitXVals();
    mAccelerometerZSeries = new SimpleXYSeries("Z");
    mAccelerometerZSeries.useImplicitXVals();
    mAccelerometerMSeries = new SimpleXYSeries("magnitude");
    mAccelerometerMSeries.useImplicitXVals();

    mFftSeries = new SimpleXYSeries("FFT");
    mFftSeries.useImplicitXVals();

    mFftPlot.addSeries(mFftSeries, new LineAndPointFormatter(Color.rgb(0, 0, 0), null, null, null));

    mAccelerometerPlot.addSeries(mAccelerometerXSeries,
            new LineAndPointFormatter(Color.rgb(100, 100, 200), null, null, null));
    mAccelerometerPlot.addSeries(mAccelerometerYSeries,
            new LineAndPointFormatter(Color.rgb(100, 200, 100), null, null, null));
    mAccelerometerPlot.addSeries(mAccelerometerZSeries,
            new LineAndPointFormatter(Color.rgb(200, 100, 100), null, null, null));
    mAccelerometerPlot.addSeries(mAccelerometerMSeries,
            new LineAndPointFormatter(Color.rgb(0, 0, 0), null, null, null));
    mAccelerometerPlot.setDomainStepValue(5);
    mAccelerometerPlot.setTicksPerRangeLabel(3);
    mAccelerometerPlot.setDomainLabel("Sample Index");
    mAccelerometerPlot.getDomainLabelWidget().pack();
    mAccelerometerPlot.setRangeLabel("m/s^2");
    mAccelerometerPlot.getRangeLabelWidget().pack();

    final PlotStatistics histStats = new PlotStatistics(1000, false);
    mAccelerometerPlot.addListener(histStats);

    // perform hardware accelerated rendering of the plots
    mAccelerometerPlot.setLayerType(View.LAYER_TYPE_NONE, null);
    mFftPlot.setLayerType(View.LAYER_TYPE_NONE, null);

    mFftPlot.setTicksPerRangeLabel(5);
    mFftPlot.setTicksPerDomainLabel(1);

    mSampleRateSeekBar = (SeekBar) findViewById(R.id.sampleRateSeekBar);
    mSampleRateSeekBar.setMax((SAMPLE_MAX_VALUE - SAMPLE_MIN_VALUE) / SAMPLE_STEP);
    mSampleRateSeekBar.setOnSeekBarChangeListener(this);

    mFftWindowSeekBar = (SeekBar) findViewById(R.id.fftWindowSeekBar);
    mFftWindowSeekBar.setMax((WINDOW_MAX_VALUE - WINDOW_MIN_VALUE) / WINDOW_STEP);
    mFftWindowSeekBar.setOnSeekBarChangeListener(this);

    mWindowSizeTextView = (TextView) findViewById(R.id.windowSizeTextView);

    // Perform FFT calculations in background thread
    mFft = new FFT(mWindowSize);
    Runnable r = new PerformFft();
    mFftThread = new Thread(r);
    mFftThread.start();

    mNotificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_help_outline_black_24dp).setContentTitle("MIS Ex3 Activity Recognizer")
            .setContentText("Trying to guess your activity").setOngoing(true);

    Intent resultIntent = new Intent(this, MainActivity.class);

    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    stackBuilder.addParentStack(MainActivity.class);
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
    mNotificationBuilder.setContentIntent(resultPendingIntent);

    mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify(mNotificationId, mNotificationBuilder.build());

    Runnable detectActivity = new DetectActivity();
    mDetectActivityThread = new Thread(detectActivity);
    mDetectActivityThread.start();
}

From source file:org.opendatakit.sensors.manager.ODKSensorManager.java

public void initializeRegisteredSensors() {

    // discover built in sensors
    android.hardware.SensorManager builtInSensorManager = (android.hardware.SensorManager) svcContext
            .getSystemService(Context.SENSOR_SERVICE);
    if (builtInSensorManager != null) {
        List<android.hardware.Sensor> deviceSensors = builtInSensorManager
                .getSensorList(android.hardware.Sensor.TYPE_ALL);
        for (android.hardware.Sensor hwSensor : deviceSensors) {
            BuiltInSensorType sensorType = BuiltInSensorType.convertToBuiltInSensor(hwSensor.getType());
            if (sensorType != null) {
                try {
                    String id = sensorType.name();
                    //Log.d(TAG,"Found sensor "+ id);
                    ODKSensor sensor = new ODKBuiltInSensor(sensorType, builtInSensorManager, id);
                    sensors.put(id, sensor);
                } catch (Exception e) {
                    e.printStackTrace();
                }/*from   ww  w . j  av  a2  s .  c  om*/
            }
        }
    }

    // load sensors from the database      
    for (ChannelManager channelManager : channelManagers.values()) {
        CommunicationChannelType type = channelManager.getCommChannelType();
        Log.d(TAG, "Load from DB:" + type.name());

        List<SensorData> savedSensorList = databaseManager.sensorList(type);

        for (SensorData sensorData : savedSensorList) {
            Log.d(TAG, "Sensor in DB:" + sensorData.id + " Type:" + sensorData.type);
            DriverType driverType = getDriverType(sensorData.type);

            if (driverType != null) {
                Log.d(TAG, "initing sensor from DB: id: " + sensorData.id + " driverType: " + sensorData.type
                        + " state " + sensorData.state);

                if (connectToDriver(sensorData.id, driverType)) {
                    Log.d(TAG, sensorData.id + " connected to driver " + sensorData.type);

                    if (sensorData.state == DetailedSensorState.CONNECTED) {
                        try {
                            channelManager.sensorConnect(sensorData.id);
                            //                        updateSensorState(sensorData.id, DetailedSensorState.CONNECTED);
                            Log.d(TAG, "connected to sensor " + sensorData.id + " over "
                                    + channelManager.getCommChannelType());
                        } catch (SensorNotFoundException snfe) {
                            updateSensorState(sensorData.id, DetailedSensorState.DISCONNECTED);
                            Log.d(TAG, "SensorNotFoundException. unable to connect to sensor " + sensorData.id
                                    + " over " + channelManager.getCommChannelType());
                        }
                    }
                }
            } else {
                Log.e(TAG, "driver NOT FOUND for type : " + sensorData.type);
            }
        }
    }
}

From source file:com.kircherelectronics.androidlinearacceleration.sensor.AccelerationSensor.java

/**
 * Initialize the state.//  w  w  w.  j a  va2  s .  c  o  m
 * 
 * @param context
 *            the Activities context.
 */
public AccelerationSensor(Context context) {
    super();

    this.context = context;

    // initEulerRotations();
    initQuaternionRotations();

    observersAcceleration = new ArrayList<AccelerationSensorObserver>();

    sensorManager = (SensorManager) this.context.getSystemService(Context.SENSOR_SERVICE);
}

From source file:com.artioml.practice.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);/*from  w w  w .  j av  a2  s .c o m*/

    ImageButton settingsButton = (ImageButton) findViewById(R.id.settingsButton);
    settingsButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            MainSettingsDialog mainSettingsDialog = new MainSettingsDialog(MainActivity.this);
            mainSettingsDialog.show();
        }
    });

    fillSettingsPanel();

    AudioAttributes.Builder attrBuilder = new AudioAttributes.Builder();
    attrBuilder.setUsage(AudioAttributes.USAGE_GAME);

    SoundPool.Builder builder = new SoundPool.Builder();
    builder.setMaxStreams(1);
    builder.setAudioAttributes(attrBuilder.build());

    soundPool = builder.build();

    soundMap = new SparseIntArray(1);
    soundMap.put(0, soundPool.load(getBaseContext(), R.raw.fire, 1));

    punchButton = (Button) findViewById(R.id.punchButton);
    punchButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            punchButton.setEnabled(false);
            (new Handler()).postDelayed(new Runnable() {

                @Override
                public void run() {
                    soundPool.play(soundMap.get(0), 1, 1, 1, 0, 1f);

                    reaction = 0.00f;
                    maxAcceleration = 0;
                    count = 0;

                    data = new ArrayList<>();

                    SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);

                    sensorManager.registerListener(sensorEventListener,
                            sensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION), 1000);
                }
            }, 2000);
        }
    });

    Button historyButton = (Button) findViewById(R.id.historyButton);
    historyButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent historyIntent = new Intent(MainActivity.this, HistoryActivity.class);
            startActivity(historyIntent);
        }
    });

}

From source file:com.example.android.jumpingjack.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.jj_layout);/*from ww  w. j  av a 2s.  c  om*/
    setupViews();
    mHandler = new Handler();
    mJumpCounter = Utils.getCounterFromPreference(this);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    renewTimer();
    mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY);
}

From source file:com.hyung.jin.seo.getup.wear.G3tUpActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_layout);
    setUpThreshold();/*from w w w.  j a  va  2s.  co  m*/
    prepareCommunication();

    status = G3tUpConstants.COUNTER_STATE; // first fragment
    selectFragment();
    sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    sensor = sensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY);
}

From source file:com.ebrain.mazeball.BluetoothChatFragment.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);//from  ww w . j  av a2  s .  c o  m
    // Get local Bluetooth adapter
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    FragmentActivity activity = getActivity();
    // If the adapter is null, then Bluetooth is not supported
    if (mBluetoothAdapter == null) {
        Toast.makeText(activity, "Bluetooth is not available", Toast.LENGTH_SHORT).show();
        activity.finish();
    }

    // Get an instance of the SensorManager
    mSensorManager = (SensorManager) activity.getSystemService(Context.SENSOR_SERVICE);
    mSensor = new MySensor();

    activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}

From source file:com.kircherelectronics.androidlinearacceleration.sensor.LinearAccelerationSensor.java

/**
 * Initialize the state.//from w  w w . j  a va  2 s.  c o m
 * 
 * @param context
 *            the Activities context.
 */
public LinearAccelerationSensor(Context context) {
    super();

    this.context = context;

    // initEulerRotations();
    initQuaternionRotations();

    observersAcceleration = new ArrayList<LinearAccelerationSensorObserver>();

    sensorManager = (SensorManager) this.context.getSystemService(Context.SENSOR_SERVICE);
}

From source file:com.kircherelectronics.gyroscopeexplorer.activity.GyroscopeActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_gyroscope);
    dataLogger = new DataLoggerManager(this);
    meanFilter = new MeanFilter();
    sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    initUI();/*from   ww  w  . jav  a2 s. c o m*/
}