磁场传感器

  
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.util.AttributeSet;
import android.view.View;

public class PointerView extends View implements SensorEventListener {
    private SensorManager sensorManager;//传感器管理器
    private Bitmap pointer=null;//定义指针的位图对象
    private float[] allvalue;//磁场传感器的值

    public PointerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        //获取传感器管理器
        sensorManager= (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
        //为传感器注册监听器
        sensorManager.registerListener(this
                ,sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD)
                ,sensorManager.SENSOR_DELAY_GAME);

        pointer= BitmapFactory.decodeResource(super.getResources(),R.drawable.pointer);//指定要绘制的指针位图

    }

    @Override
    public void onSensorChanged(SensorEvent event) {//传感器值改变时触发

        if(event.sensor.getType()==Sensor.TYPE_MAGNETIC_FIELD){
            float[] value=event.values;//获取磁场感应器的值
            allvalue=value;
            super.postInvalidate();
        }

    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {//传感器精度改变时触发

    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //根据xy轴磁场强度绘制指针
        if(allvalue!=null){
            float x=allvalue[0];
            float y=allvalue[1];
            canvas.save();
            canvas.restore();//重置绘图对象
            canvas.translate(super.getWidth()/2,super.getHeight()/2);//设置旋转的中心点为屏幕的中心点
            if(y==0&x>0){//正东方
                canvas.rotate(90);//旋转90度
            }else if(y==0&x<0){//正西方
                canvas.rotate(270);
            }else{
             if(y>=0){
                canvas.rotate((float) Math.tanh(x/y)*90);
             }else {
                 canvas.rotate(180+(float) Math.tanh(x/y)*90);
                 }
            }
        }
        canvas.drawBitmap(this.pointer,-this.pointer.getWidth()/2,-this.pointer.getHeight()/2
                ,new Paint());//绘制指针

    }
}

你可能感兴趣的:(磁场传感器)