加速度传感器


  
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Vibrator;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements SensorEventListener {
    private SensorManager sensorManager;
    private Vibrator vibrator;//振动器
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        sensorManager= (SensorManager) getSystemService(Context.SENSOR_SERVICE);//获取传感器管理器
        vibrator= (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);//获取振动器
    }

    @Override
    protected void onResume() {
        super.onResume();
        sensorManager.registerListener(this
                ,sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)
                ,SensorManager.SENSOR_DELAY_GAME);//为加速度传感器注册监听器

    }

    @Override
    public void onSensorChanged(SensorEvent event) {

        int sensorType = event.sensor.getType();//获取传感器类型
        if (sensorType==Sensor.TYPE_ACCELEROMETER) {
            float[]values=event.values;//获取传感器的值
            if(values[0]>15||values[1]>15||values[2]>10){
                Toast.makeText(this, "摇一摇成功", Toast.LENGTH_SHORT).show();
                AlertDialog.Builder alertDialog=new AlertDialog.Builder(this);//创建对话框构建器
                alertDialog.setView(R.layout.open);//设置布局文件
                alertDialog.show();//显示对话框
                vibrator.vibrate(500);//设置振动器频率
                sensorManager.unregisterListener(this);
            }

        }
    }

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

    }
}

你可能感兴趣的:(加速度传感器)