Andorid传感器之摇一摇

package com.llm;



import java.util.List;



import android.app.Activity;

import android.hardware.Sensor;

import android.hardware.SensorEvent;

import android.hardware.SensorEventListener;

import android.hardware.SensorManager;

import android.os.Bundle;

import android.widget.Toast;



public class TestSensorActivity

    extends Activity {

    private static final int FORCE_THRESHOLD = 900;

    private long lastShakeTime;//

    private long presentShakeTime;

    private long duration;// 时间差

    private float lastX = 0.0f;

    private float lastY = 0.0f;

    private float lastZ = 0.0f;

    private float presentX = 0.0f;

    private float presentY = 0.0f;

    private float presentZ = 0.0f;

    private float currenForce;// 摇动的速率



    @Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        SensorManager sm = (SensorManager) getSystemService(SENSOR_SERVICE);

        List<Sensor> ls = sm.getSensorList(Sensor.TYPE_ACCELEROMETER);

        if (ls.size() > 0) {

            Sensor s = ls.get(0);

            sm.registerListener(new SensorEventListener() {



                public void onSensorChanged(SensorEvent event) {

                    // 如果有一个条件为真则return

                    if (event.sensor.getType() != Sensor.TYPE_ACCELEROMETER || event.values.length < 3)

                        return;

                    presentX = event.values[SensorManager.DATA_X];

                    presentY = event.values[SensorManager.DATA_Y];

                    presentZ = event.values[SensorManager.DATA_Z];

                    presentShakeTime = System.currentTimeMillis();

                    if (presentShakeTime - lastShakeTime > 100) {

                        duration = (presentShakeTime - lastShakeTime);

                        lastShakeTime = presentShakeTime;

                        currenForce =

                            Math.abs(presentX + presentY + presentZ - lastX - lastY - lastZ) / duration *

                                10000;

                        if (currenForce > FORCE_THRESHOLD) {// 摇动的速率>900

                            Toast.makeText(TestSensorActivity.this, "摇一摇成功", 1000).show();

                        }

                        lastX = presentX;

                        lastY = presentY;

                        lastZ = presentZ;

                    }

                };



                public void onAccuracyChanged(Sensor sensor, int accuracy) {



                }

            }, s, SensorManager.SENSOR_DELAY_NORMAL);

        }

    }

}

你可能感兴趣的:(andorid)