栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Android开发:指南针(基于手机传感器)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Android开发:指南针(基于手机传感器)

Android基于多种手机传感器开发指南针的项目

1、基于方向传感器
2、基于加速度传感器和磁场传感器

基于方向传感器的指南针

Java代码——TypeOneActivity.java文件

package com.example.compass00;

import android.app.Activity;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;

import java.util.List;

public class TypeOneActivity extends Activity implements View.OnClickListener, SensorEventListener {
    //使用方向传感器编写指南针
    public SensorManager sensorManager;
    private float currentDegree;
    private TextView tvDirection;       //指南针文字显示方位控件
    private float azimuth = 0f;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        currentDegree = 0f;
        sensorManager = (SensorManager) this.getSystemService(SENSOR_SERVICE);

        setContentView(R.layout.compass00);

        TextView return00 = findViewById(R.id.retuen);
        return00.setOnClickListener(this);

        TextView exit = findViewById(R.id.exit);
        exit.setOnClickListener(this);

        tvDirection = (TextView) findViewById(R.id.value01);
    }

    @Override
    public void onResume() {
        //为方向传感器注册监听器
        super.onResume();
        List sensors = sensorManager.getSensorList(Sensor.TYPE_ORIENTATION);
        for (Sensor s : sensors) {
            sensorManager.registerListener(this, s, SensorManager.SENSOR_DELAY_FASTEST);
        }
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.retuen:
                intent = new Intent(this, MainActivity.class);
                startActivity(intent);
                finish();
                break;
            case R.id.exit:
                intent = new Intent(Intent.ACTION_MAIN);
                intent.addCategory(Intent.CATEGORY_HOME);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
                finish();
                break;
        }
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        TextView value = findViewById(R.id.value);
        ImageView imageView = findViewById(R.id.compass);
        float[] values = event.values;
        StringBuilder stringBuilder = new StringBuilder();
        if (event.sensor.getType() == Sensor.TYPE_ORIENTATION) {
            stringBuilder.append("方向传感器的返回值:");
            stringBuilder.append("nvalues[0]:" + values[0]);
            stringBuilder.append("nvalues[1]:" + values[1]);
            stringBuilder.append("nvalues[2]:" + values[2]);
            value.setText(stringBuilder.toString());
            float degree = event.values[0];     //取围绕z轴转过的角度
            azimuth = (degree + 360) % 360;
            RotateAnimation rotateAnimation = new RotateAnimation(currentDegree, -degree, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
            if (azimuth <= 15 || azimuth >= 345) {
                tvDirection.setText("方位:北");
            } else if (15 < azimuth && azimuth < 75) {
                tvDirection.setText("方位:东北");
            } else if (75 <= azimuth && azimuth <= 105) {
                tvDirection.setText("方位:东");
            } else if (105 < azimuth && azimuth < 165) {
                tvDirection.setText("方位:东南");
            } else if (165 <= azimuth && azimuth <= 195) {
                tvDirection.setText("方位:南");
            } else if (195 < azimuth && azimuth < 255) {
                tvDirection.setText("方位:西南");
            } else if (255 <= azimuth && azimuth <= 285) {
                tvDirection.setText("方位:西");
            } else if (285 < azimuth && azimuth < 345) {
                tvDirection.setText("方位:西北");
            }

            rotateAnimation.setDuration(200);
            rotateAnimation.setFillAfter(true);
            imageView.setAnimation(rotateAnimation);
            currentDegree = -degree;
        }
    }
    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }
}

布局文件——compass00.xml文件




    

        

            

            

            

            
        

        

        

    


基于加速度传感器和磁场传感器

Java代码——TypeTwoActivity.Java文件

package com.example.compass00;

import android.app.Activity;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;


public class TypeTwoActivity extends Activity implements View.OnClickListener, SensorEventListener {
    //通过加速度传感器和地磁传感器编写指南针
    public SensorManager sensorManager;
    private Sensor aSensor;     //定义加速度传感器
    private Sensor mSensor;     //定义磁场传感器

    private String TAG = "CompassActivity";
    public ImageView ivArrow;     //指南针指针控件
    private TextView tvDirection;       //指南针文字显示方位控件

    private float[] mGravity = new float[3];
    private float[] mGeomagnetic = new float[3];

    private float azimuth = 0f;
    private float currentAzimuth = 0;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.compass01);

        TextView return00 = findViewById(R.id.retuen);
        return00.setOnClickListener(this);

        TextView exit = findViewById(R.id.exit);
        exit.setOnClickListener(this);

        initView();
        initData();
    }

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

    @Override

    protected void onResume() {
        super.onResume();
        if (null != sensorManager) {
// 注册陀螺仪传感器
            sensorManager.registerListener(this, aSensor,
                    SensorManager.SENSOR_DELAY_GAME);

// 注册磁场传感器
            sensorManager.registerListener(this, mSensor,
                    SensorManager.SENSOR_DELAY_GAME);
        }
    }

    @Override

    protected void onPause() {
        super.onPause();
        if (null != sensorManager) {
            sensorManager.unregisterListener(this);     // 取消注册陀螺仪传感器
        }
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.retuen:
                intent = new Intent(this, MainActivity.class);
                startActivity(intent);
                finish();
                break;
            case R.id.exit:
                intent = new Intent(Intent.ACTION_MAIN);
                intent.addCategory(Intent.CATEGORY_HOME);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
                finish();
                break;
        }
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        final float alpha = 0.97f;

        synchronized (this) {
//指南针转动角度算法
//判断当前是加速度感应器还是地磁感应器
            if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
                TextView value00 = findViewById(R.id.value00);
                float[] values = event.values;
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append("加速度计的返回值:");
                stringBuilder.append("nvalues[0]:" + values[0]);
                stringBuilder.append("nvalues[1]:" + values[1]);
                stringBuilder.append("nvalues[2]:" + values[2]);
                value00.setText(stringBuilder.toString());
                mGravity[0] = alpha * mGravity[0] + (1 - alpha)
                        * event.values[0];
                mGravity[1] = alpha * mGravity[1] + (1 - alpha)
                        * event.values[1];
                mGravity[2] = alpha * mGravity[2] + (1 - alpha)
                        * event.values[2];
            }

            if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
                TextView value01 = findViewById(R.id.value01);
                float[] values = event.values;
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append("磁场传感器的返回值:");
                stringBuilder.append("nvalues[0]:" + values[0]);
                stringBuilder.append("nvalues[1]:" + values[1]);
                stringBuilder.append("nvalues[2]:" + values[2]);
                value01.setText(stringBuilder.toString());
                mGeomagnetic[0] = alpha * mGeomagnetic[0] + (1 - alpha)
                        * event.values[0];
                mGeomagnetic[1] = alpha * mGeomagnetic[1] + (1 - alpha)
                        * event.values[1];
                mGeomagnetic[2] = alpha * mGeomagnetic[2] + (1 - alpha)
                        * event.values[2];
            }

            float R[] = new float[9];
            float I[] = new float[9];
            boolean success = SensorManager.getRotationMatrix(R, I, mGravity,
                    mGeomagnetic);
            if (success) {
                float orientation[] = new float[3];
                SensorManager.getOrientation(R, orientation);
                azimuth = (float) Math.toDegrees(orientation[0]); // orientation
                azimuth = (azimuth + 360) % 360;

                adjustArrow();

            }
        }
    }

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

    }

    
    private void initView() {
        ivArrow = (ImageView) findViewById(R.id.compass);
        tvDirection = (TextView) findViewById(R.id.value02);
    }

    
    private void initData() {
        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        aSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        mSensor = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
    }

    
    private void adjustArrow() {
        if (ivArrow == null) {
            return;
        }

        Animation an = new RotateAnimation(-currentAzimuth, -azimuth,
                Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
                0.5f);
        currentAzimuth = azimuth;
        Log.i(TAG, "azimuth:" + azimuth);

        if (azimuth <= 15 || azimuth >= 345) {
            tvDirection.setText("方位:北");
        } else if (15 < azimuth && azimuth < 75) {
            tvDirection.setText("方位:东北");
        } else if (75 <= azimuth && azimuth <= 105) {
            tvDirection.setText("方位:东");
        } else if (105 < azimuth && azimuth < 165) {
            tvDirection.setText("方位:东南");
        } else if (165 <= azimuth && azimuth <= 195) {
            tvDirection.setText("方位:南");
        } else if (195 < azimuth && azimuth < 255) {
            tvDirection.setText("方位:西南");
        } else if (255 <= azimuth && azimuth <= 285) {
            tvDirection.setText("方位:西");
        } else if (285 < azimuth && azimuth < 345) {
            tvDirection.setText("方位:西北");
        }

        an.setDuration(200);
        an.setRepeatCount(0);
        an.setFillAfter(true);

        ivArrow.startAnimation(an);//动画效果转动传感器
    }
}


布局文件——compass01.xml




    

        

            

            

            

            

            

        

        

        

    


app效果图




全部的资源文件已进整个项目代码我已经放在了CSDN中,需要的可以自取https://download.csdn.net/download/weixin_45655279/85545175

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/951058.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号