摇动传感器不工作

时间:2014-01-23 21:45:31

标签: java android sensor gravity shake

我希望我的震动传感器工作。摇动我的Android手机让事情发生,现在当我摇动手机时没有任何反应。我的代码如下:

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

和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;

关于活动

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(); 
            }

        }
   };

1 个答案:

答案 0 :(得分:1)

您好我在这里添加了Shake Sensor的示例源代码。请尝试此示例。希望它对您有所帮助。如果您有任何问题,请告诉我。感谢。

<强> 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);
    }
}

请添加AndroidManifest权限。

<uses-permission android:name="android.permission.VIBRATE" />