码迷,mamicode.com
首页 > 移动开发 > 详细

Android的加速度传感器模拟摇一摇的效果-android学习之旅(66)

时间:2015-08-07 22:28:59      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:android

主要介绍一下android的加速传感器的简单用法,模拟摇一摇 ,如果x,y,z三个方向的加速度超过了15,就会弹出Toast,当然你可以设置更复杂的策略,比如判断间隔

代码如下

public class MainActivity extends Activity {
    private SensorManager sensorManager;
    private TextView textView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        sensorManager.registerListener(sensorEventListener,sensor,SensorManager.SENSOR_DELAY_NORMAL);
    }
    private SensorEventListener sensorEventListener = new SensorEventListener() {
        @Override
        public void onSensorChanged(SensorEvent sensorEvent) {
            float xValue = Math.abs(sensorEvent.values[0]);
            float yValue = Math.abs(sensorEvent.values[1]);
            float zvalue = Math.abs(sensorEvent.values[2]);
            if (xValue > 15||yValue > 15||zvalue > 15){
                Toast.makeText(MainActivity.this,"摇一摇",Toast.LENGTH_LONG).show();
            }
        }

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

        }
    };
    @Override
    protected void onDestroy() {
        if (sensorManager != null){
            sensorManager.unregisterListener(sensorEventListener);
        }
        super.onDestroy();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

Android的加速度传感器模拟摇一摇的效果-android学习之旅(66)

标签:android

原文地址:http://blog.csdn.net/lpjishu/article/details/47344647

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!