摇一摇代码

摇一摇代码

 

package com.yaoyiyao;

 

import android.annotation.*;

import android.app.*;

import android.hardware.*;

import android.media.*;

import android.os.*;

import android.widget.*;

import com.yaoyiyao.*;

 

public class TestSensorActivity extends Activity {

private SensorManager sensorManager;

private Sensor sensor;

private Vibrator vibrator;

private static final int UPTATE_INTERVAL_TIME = 70;//两次检测的时间间隔

private static final int SPEED_SHRESHOLD = 30;//这个值调节灵敏度

private long lastUpdateTime;

private float lastX;

private float lastY;

private float lastZ;

 

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);

vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);

}

@Override

protected void onResume() {

// TODO Auto-generated method stub

super.onResume();

if (sensorManager != null) {

sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

}

if (sensor != null) {

sensorManager.registerListener(sensorEventListener,sensor,SensorManager.SENSOR_DELAY_GAME);//这里选择感应频率

}

}

/**

* 重力感应监听

*/

private SensorEventListener sensorEventListener = new SensorEventListener()

{

@Override

public void onSensorChanged(SensorEvent event)

{

// 现在检测时间

long currentUpdateTime = System.currentTimeMillis();

// 两次检测的时间间隔

long timeInterval = currentUpdateTime – lastUpdateTime;

// 判断是否达到了检测时间间隔

if (timeInterval < UPTATE_INTERVAL_TIME)

         return;

         // 现在的时间变成last时间

         lastUpdateTime = currentUpdateTime;

        // 传感器信息改变时执行该方法

        float[] values = event.values;

        float x = values[0]; // x轴方向的重力加速度,向右为正

        float y = values[1]; // y轴方向的重力加速度,向前为正

        float z = values[2]; // z轴方向的重力加速度,向上为正

        float deltaX = x – lastX;

        float deltaY = y – lastY;

        float deltaZ = z – lastZ;

        lastX = x;

        lastY = y;

        lastZ = z;

        double speed = (Math.sqrt(deltaX * deltaX + deltaY * deltaY

                      + deltaZ * deltaZ) / timeInterval) * 100;

        if (speed >= SPEED_SHRESHOLD)

{

vibrator.vibrate(200);

Toast.makeText(TestSensorActivity.this, “检测到摇晃,执行操作!”, Toast.LENGTH_SHORT).show();//事件

}

}

@Override

public void onAccuracyChanged(Sensor sensor, int accuracy){

}

};

 

@Override

public void onBackPressed()

{

int pid = android.os.Process.myPid();

android.os.Process.killProcess(pid);

}

}

来自坤少论坛—http://kunshao.cn01.cf/

© 版权声明
THE END
喜欢就支持以下吧
点赞0赞赏
分享
评论 抢沙发

请登录后发表评论