指南针

本文介绍了一款基于Android平台的指南针应用开发过程。通过融合使用加速度传感器和磁力传感器的数据,实现了设备方向的实时监测与显示。文章详细展示了如何获取传感器数据,并通过旋转矩阵与方位角计算来确定设备的指向。
摘要由CSDN通过智能技术生成

这么简单的东西就啥也不说了

package com.example.linj.mysensorapplication;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {
    private SensorManager sensorManager;
    private ImageView mImage;
    private float degree;
    private float rotateDegree;
    private MyView myView;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0x11:
                    myView.setDegree(rotateDegree);
                    handler.sendEmptyMessageDelayed(0x11,40);
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myView = (MyView) findViewById(R.id.my_compass);
//        mImage = (ImageView) findViewById(R.id.image);
        sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        Sensor magneticSensor = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
        Sensor accelerometerSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        sensorManager.registerListener(listener,magneticSensor,SensorManager.SENSOR_DELAY_GAME);
        sensorManager.registerListener(listener,accelerometerSensor,SensorManager.SENSOR_DELAY_GAME);

    }

    @Override
    protected void onDestroy() {
    //在活动结束时注册掉监听器
        super.onDestroy();
        if (sensorManager != null){
            sensorManager.unregisterListener(listener);
        }
    }

    private SensorEventListener listener = new SensorEventListener() {
        float[] accelerometerValues = new float[3];
        float[] magneticValues = new float[3];

        @Override
        public void onSensorChanged(SensorEvent event) {
            if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER){
                accelerometerValues = event.values.clone();
            }else if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD){
                magneticValues = event.values.clone();
            }
            float[] R = new float[9];
            float[] values = new float[3];
            SensorManager.getRotationMatrix(R, null, accelerometerValues, magneticValues);
            SensorManager.getOrientation(R, values);
            Log.d("lu", "角度" + Math.toDegrees(values[0]));
            rotateDegree = -(float) Math.toDegrees(values[0]);
            if (Math.abs(rotateDegree)-degree > 1) {
                handler.sendEmptyMessage(0x11);
                degree = rotateDegree;
            }
//            if (Math.abs(rotateDegree)-degree > 1){
//                RotateAnimation animation = new RotateAnimation(degree,rotateDegree, Animation.RELATIVE_TO_SELF,0.5f, Animation.RELATIVE_TO_SELF,0.5f);
//                animation.setFillAfter(true);
//                mImage.startAnimation(animation);
//                degree = rotateDegree;
//            }
        }

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

        }
    };
}

//自定义一个View用来显示
package com.example.linj.mysensorapplication;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

/**
 * Created by Administrator on 2015/9/21.
 */
public class MyView extends SurfaceView {
    private int width;
    private int height;
    private boolean isTrue;
    private Canvas canvas;
    private Paint paint;
    private Paint paintLine;
    private Paint paintLine1;
    private  Paint paintText;
    private Path path;
    private Path path1;
    private SurfaceHolder surfaceHolder;
    private float degree;
    private float x;
    private float y;
    private float r;

    public MyView(Context context) {
        super(context);
    }

    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        surfaceHolder = getHolder();
        surfaceHolder.addCallback(callback);
        paint = new Paint();
        paint.setAntiAlias(true);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(4);
        paint.setColor(Color.BLACK);
        paintLine = new Paint();
        paintLine1 = new Paint();
        paintText = new Paint();
        paintLine.setAntiAlias(true);
        paintLine.setStrokeWidth(2);
        paintLine.setColor(Color.RED);
        paintLine1.setAntiAlias(true);
        paintLine1.setStrokeWidth(2);
        paintLine1.setColor(Color.BLUE);
        paintText.setAntiAlias(true);
        paintText.setColor(Color.BLUE);
        paintText.setTextSize(36);
        path = new Path();
        path1 = new Path();
    }

    SurfaceHolder.Callback callback = new SurfaceHolder.Callback() {
        @Override
        public void surfaceCreated(final SurfaceHolder holder) {
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    isTrue = true;
                    while (isTrue){
                        canvas = holder.lockCanvas();
                        canvas.drawColor(Color.WHITE);//x = width/2;y = height/2; r = width/5;
                        canvas.drawCircle(x, y, r, paint);
                        canvas.drawText("N", x-10, y-r+30, paintText);
                        canvas.drawText("E", x+r-24, y+10, paintText);
                        canvas.drawText("S", x-10, y+r-10, paintText);
                        canvas.drawText("W", x-r+4, y+10, paintText);
                        paintDir();
                        holder.unlockCanvasAndPost(canvas);
                        try {
                            Thread.sleep(40);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
            thread.start();
        }

        private void paintDir() {
            canvas.save();
            canvas.rotate(degree, x, y);
            path.moveTo(x-9, y);
            path.lineTo(x, y-r/2);
            path.lineTo(x+9, y);
            canvas.drawPath(path, paintLine);
            path1.moveTo(x-9, y);
            path1.lineTo(x, y+r/2);
            path1.lineTo(x+9, y);
            canvas.drawPath(path1, paintLine1);
            canvas.restore();
        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
            isTrue = false;
        }
    };

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        width = getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec);
        height = getDefaultSize(getSuggestedMinimumHeight(),heightMeasureSpec);
        setMeasuredDimension(width, height);
        x = width/2;
        y = height/2;
        r = width/5;
    }

    @Override
    public SurfaceHolder getHolder() {
        return super.getHolder();
    }

    public void setDegree(float degree) {
        this.degree = degree;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值