传感器:方向 、重力、磁场、温度、近距离、压力、光线、加速度
下面是如何使用方向传感器(指南针):
使用自定义view画出指南针
public class MainActivity extends Activity{ private SensorManager manager; private Sensor mSensor; float[] mValues; private SampleView mView; @SuppressWarnings("deprecation") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mView = new SampleView(this);//使用自定义view setContentView(mView); //得到传感器管理器 manager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); //得到方向传感器 mSensor = manager.getDefaultSensor(Sensor.TYPE_ORIENTATION); } SensorEventListener mListener = new SensorEventListener() { @Override public void onSensorChanged(SensorEvent event) { mValues = event.values; if (mView != null) { mView.invalidate();//event发生改变时,重绘 } } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { //精确改变,适用游戏 } }; @Override protected void onStart() { super.onStart(); //在onstart()或onresume()里,管理器注册监听事件 manager.registerListener(mListener, mSensor, SensorManager.SENSOR_DELAY_GAME); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } private class SampleView extends View { private Paint mPaint = new Paint(); private Path mPath = new Path(); private boolean mAnimate; private long mNextTime; public SampleView(Context context) { super(context); // Construct a wedge-shaped path mPath.moveTo(0, -50); mPath.lineTo(-20, 60); mPath.lineTo(0, 50); mPath.lineTo(20, 60); mPath.close(); } @Override protected void onDraw(Canvas canvas) { Paint paint = mPaint; canvas.drawColor(Color.WHITE); paint.setAntiAlias(true); paint.setColor(Color.BLACK); paint.setStyle(Paint.Style.FILL); int w = canvas.getWidth(); int h = canvas.getHeight(); int cx = w / 2; int cy = h / 2; canvas.translate(cx, cy); if (mValues != null) { canvas.rotate(-mValues[0]); } canvas.drawPath(mPath, mPaint); } @Override protected void onAttachedToWindow() { mAnimate = true; super.onAttachedToWindow(); } @Override protected void onDetachedFromWindow() { mAnimate = false; super.onDetachedFromWindow(); } }}