Question

I want my shake sensor to work.On shaking my android phone to make something happen, right now nothing happens when i shake my phone. My code is as below:

private SensorManager mSensorManager;
    private float mAccel; // acceleration apart from gravity
    private float mAccelCurrent; // current acceleration including gravity
    private float mAccelLast; // last acceleration including gravity

and oncreate:

mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        mSensorManager.registerListener(mSensorListener, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
        mAccel = 0.00f;
        mAccelCurrent = SensorManager.GRAVITY_EARTH;
        mAccelLast = SensorManager.GRAVITY_EARTH;

on acitvity

private final SensorEventListener mSensorListener = new SensorEventListener() {

        public void onSensorChanged(SensorEvent se) {
          float x = se.values[0];
          float y = se.values[1];
          float z = se.values[2];
          mAccelLast = mAccelCurrent;
          mAccelCurrent = FloatMath.sqrt(x*x + y*y + z*z);
          float delta = mAccelCurrent - mAccelLast;
          mAccel = mAccel * 0.9f + delta * 0.1f; // perform low-cut filter
        }

        public void onAccuracyChanged(Sensor sensor, int accuracy) {
            if(mAccel > 0.1)
            {
             Toast toast = Toast.makeText(getApplicationContext(), "Device has shaken.", Toast.LENGTH_LONG); toast.show(); 
            }

        }
   };
Was it helpful?

Solution

Hi Here i added sample source code for Shake Sensor .Please try this example. Hope it should helpful for you.Please let me know if you have any issues. Thanks.

main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_above="@+id/footer"
    android:padding="10dp"
    android:background="#eaeae8" >

    <TextView
        android:id="@+id/txtSettings"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" 
        android:padding="10dp"
        android:text="Enable and Disable the Sensor">

    </TextView>

    <TextView 
            android:id="@+id/label"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:padding="10dip"
        android:textSize="16sp"
        android:textStyle="bold" >
        </TextView>

        <RadioGroup
            android:id="@+id/sensorSettings"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@+id/txtSettings"
            android:layout_below="@+id/txtSettings"
            android:layout_marginTop="18dp" >

            <RadioButton
                android:id="@+id/enable"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Sensor Enable" />

            <RadioButton 
                android:id="@+id/disable"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Sensor Disable" />
        </RadioGroup>

</RelativeLayout>

SensorTestActivity.java

import android.app.Activity;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;

public class SensorTestActivity extends Activity implements SensorEventListener {
    private SensorManager sensorManager;
    private boolean color = false;
    private View view;
    private long lastUpdate;
    static boolean enableSensor = true;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.main);
        view = findViewById(R.id.label);
        view.setBackgroundColor(Color.GREEN);

        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        sensorManager.registerListener(this,
                sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
                SensorManager.SENSOR_DELAY_NORMAL);
        lastUpdate = System.currentTimeMillis();

        RadioGroup sensorSettings =(RadioGroup)findViewById(R.id.sensorSettings);
        sensorSettings.setOnCheckedChangeListener(new OnCheckedChangeListener(){
            @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            // checkedId is the RadioButton selected
            switch(checkedId) {
            case R.id.enable:
                enableSensor = true;
                break;
            case R.id.disable:
                enableSensor = false;
                break;
            }
        }
        });
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
            if(enableSensor){
                getAccelerometer(event);
            }           
        }

    }

    private void getAccelerometer(SensorEvent event) {
        float[] values = event.values;
        // Movement
        float x = values[0];
        float y = values[1];
        float z = values[2];

        float accelationSquareRoot = (x * x + y * y + z * z)
                / (SensorManager.GRAVITY_EARTH * SensorManager.GRAVITY_EARTH);
        long actualTime = System.currentTimeMillis();
        if (accelationSquareRoot >= 2) //
        {
            if (actualTime - lastUpdate < 200) {
                return;
            }
            lastUpdate = actualTime;
            Toast.makeText(this, "Device has shaken", Toast.LENGTH_SHORT)
                    .show();
            if (color) {
                view.setBackgroundColor(Color.GREEN);

            } else {
                view.setBackgroundColor(Color.RED);
            }
            color = !color;
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

    @Override
    protected void onResume() {
        super.onResume();
        // register this class as a listener for the orientation and
        // accelerometer sensors
        sensorManager.registerListener(this,
                sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
                SensorManager.SENSOR_DELAY_NORMAL);
    }

    @Override
    protected void onPause() {
        // unregister listener
        super.onPause();
        sensorManager.unregisterListener(this);
    }
}

Please add the AndroidManifest permission.

<uses-permission android:name="android.permission.VIBRATE" />
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top