传感器

来源:互联网 发布:cf易语言源码大全 编辑:程序博客网 时间:2024/04/28 17:05

1.主函数

public class MainActivity extends AppCompatActivity {    private Sensor acc;    private SensorManager syst;    private MySensorListener mySensorListener;    private TextView tv;    private Vibrator vi;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        //获取系统权限        syst = (SensorManager) getSystemService(Context.SENSOR_SERVICE);        //设置        acc= syst.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);        mySensorListener = new MySensorListener();        tv= (TextView) findViewById(R.id.tv);         //震动效果      震动需要在清单文件里面给权限<uses-permission android:name="android.permission.VIBRATE"></uses-permission>        vi = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);    }    @Override    protected void onResume() {        super.onResume();        //注册绑定        syst.registerListener(mySensorListener,acc,syst.SENSOR_DELAY_NORMAL);    }    @Override    protected void onPause() {        super.onPause();        //取消绑定        syst.unregisterListener(mySensorListener);    }    class MySensorListener implements SensorEventListener {        @Override        public void onSensorChanged(SensorEvent sensorEvent) {            float[] values = sensorEvent.values;            float x = values[0];            float y = values[1];            float z = values[2];            tv.setText(x+"    "+y+"    " +z);        }        @Override        public void onAccuracyChanged(Sensor sensor, int i) {        }    }}






2.布局

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main"    android:layout_width="match_parent" android:layout_height="match_parent"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context="comqq.example.hasee.myapplication.MainActivity">    <TextView        android:id="@+id/tv" android:layout_width="wrap_content" android:layout_height="wrap_content"        android:text="Hello World!" /></RelativeLayout>