简体   繁体   English

震动感应器无法运作

[英]Shake sensor is not working

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. 我希望我的震动传感器能够正常工作。在摇动Android手机以使某事发生时,现在当我摇动手机时什么也没有发生。 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: 和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(); 
            }

        }
   };

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 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 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. 请添加AndroidManifest权限。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM