Android传感器——温度传感器及重力传感器实现的小案例

接上<Android传感器——传感器监听器及摇一摇案例>

https://blog.csdn.net/nishigesb123/article/details/90258784

 

部分参考:https://developer.android.google.cn/guide/topics/sensors/sensors_overview.html


温度传感器

概述及杂项

SensorTypeDescriptionCommon Uses
TYPE_AMBIENT_TEMPERATUREHardwareMeasures the ambient room temperature in degrees Celsius (°C). See note below.Monitoring air temperatures.
SensorAndroid 4.0 
(API Level 14)
Android 2.3 
(API Level 9)
Android 2.2 
(API Level 8)
Android 1.5 
(API Level 3)
TYPE_AMBIENT_TEMPERATUREYesn/an/an/a

避免使用不推荐的方法或传感器类型

有几种方法和常量已被废弃。特别是,TYPE_ORIENTATION已不再推荐传感器类型。若要获取定向数据,应使用getOrientation()方法代替。同样,TYPE_TEMPERATURE已不再推荐传感器类型。您应该使用TYPE_AMBIENT_TEMPERATURE传感器在运行Android4.0的设备上输入。

Avoid using deprecated methods or sensor types

Several methods and constants have been deprecated. In particular, the TYPE_ORIENTATIONsensor type has been deprecated. To get orientation data you should use the getOrientation()method instead. Likewise, the TYPE_TEMPERATURE sensor type has been deprecated. You should use the TYPE_AMBIENT_TEMPERATURE sensor type instead on devices that are running Android 4.0.

示例代码

接之前的案例,布局又双叒叕加一个TextView就好

package com.example.sensor;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import java.util.List;

public class MainActivity extends AppCompatActivity {

    private TextView textView;
    private TextView textView_temp;
    private TextView textView_start;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = findViewById(R.id.content);
        textView_start = findViewById(R.id.textView_start);
        textView_temp = findViewById(R.id.textView_temp);
        //获取系统传感器管理器
        SensorManager sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        //通过系统传感器管理器..获取本机所有传感器.
        List<Sensor> sensorList = sm.getSensorList(Sensor.TYPE_ALL);

        for (Sensor s : sensorList) {
            Log.i("sensorList", s.toString());
        }
        //获取指定的某一个传感器,下面为加速度传感器
        Sensor type_accelerometer = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        if (type_accelerometer != null) {
            Log.i("type_accelerometer", type_accelerometer.toString());
        }
        //注册传感器的监听器
        sm.registerListener(new SensorEventListener() {
            @Override
            public void onSensorChanged(SensorEvent event) {
                //传感器数据变化,在该方中我们可以获取传感器变化的值
                float x = event.values[0];
                float y = event.values[1];
                float z = event.values[2];
                textView.setText("x=" + x + "y=" + y + "z=" + z);
                //  System.out.println("x="+x+",y="+y+",z="+z);
                if ((Math.abs(x) + Math.abs(y) + Math.abs(z)) >= ringValue && flag == false) {
                    flag = true;
                    textView_start.setVisibility(View.VISIBLE);
                    MediaPlayer mp = MediaPlayer.create(MainActivity.this, R.raw.test);
                    mp.start();
                    mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                        @Override
                        public void onCompletion(MediaPlayer mp) {
                            mp.release();
                            flag = false;
                            textView_start.setVisibility(View.GONE);
                        }
                    });
                }
            }

            @Override
            public void onAccuracyChanged(Sensor sensor, int accuracy) {
                //传感器精度变化
            }
        }, type_accelerometer, SensorManager.SENSOR_DELAY_NORMAL);


        //温度传感器
        Sensor type_ambient_temperature = sm.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE);
        if (type_ambient_temperature != null) {
            System.out.println(type_ambient_temperature.toString());
        }
        sm.registerListener(new SensorEventListener() {
            @Override
            public void onSensorChanged(SensorEvent event) {
                float temp = event.values[0];
                System.out.println(temp);
                temp = (float) (Math.round(temp * 10.0) / 10.0);
                textView_temp.setText("温度:" + temp + "℃");
            }

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

            }
        }, type_ambient_temperature, SensorManager.SENSOR_DELAY_NORMAL);
    }

    int ringValue = 40;//三维XYZ三个值的总和达到这个值表示为摇晃
    boolean flag = false;//表示是否已经在播放声音
}

然而,我的手机并没有温度传感器 2333 

 


自由的小方

需求分析

  1. 定义一个小方块对象
  2. 定义一个视图,用于把小方块配置到屏幕上
  3. 通过重力传感器TYPE_GRAVIY控制小方块在不超过屏幕的范围内在屏幕上自由的滚(?)

实现

准备

一个新的Activity并设置为启动页面,同时修改它的样式(主题),设置为全屏。

如?图所示

并将创建的Activity继承改为继承Activity,如?图所示

方块绘制思路

  • 准备一个类,Rect表示小方块
  • 同时准备一个继承的View类RectView(自定义视图),实现其onDraw方法
  • 使用canvas.drawRect绘制小方块

附 drawRect 相关介绍
Added in API level 1
void drawRect (float left, float top,  float right,float bottom, Paint paint)
Draw the specified Rect using the specified paint. The rectangle will be filled or framed based on the Style in the paint.
Parameters

  • left  (float) :The left side of the rectangle to be drawn
  • top (float): The top side of the rectangle to be drawn
  • right(float): The right side of the rectangle to be drawn
  • bottom(float): The bottom side of the rectangle to be drawn
  • paint(Paint): The paint used to draw the rect

 

  • 根据drawRect 的参数合理的定义Rect对象

具体实现

Rect.java

package com.example.sensor;

public class Rect {
    float left = 100, top = 100, right = 100, bottom = 100;
    private int width, height;

    public Rect(int width, int height) {
        this.width = width;
        this.height = height;
        left = width / 2 - right / 2;
        top = height / 2 - bottom / 2;

    }

    public float getBottom() {
        return bottom;
    }

    public void setBottom(float bottom) {
        this.bottom = bottom;
    }

    public float getLeft() {
        return left;
    }

    public void setLeft(float left) {
        this.left -= left;
        if (this.left <= 0) {
            this.left = 0;
        } else if (this.left >= width - this.right) {
            this.left = width - this.right;
        }
    }

    public float getRight() {
        return right;
    }

    public void setRight(float right) {
        this.right = right;
    }

    public float getTop() {
        return top;
    }

    public void setTop(float top) {
        this.top += top;
        if (this.top <= 0) {
            this.top = 0;
        } else if (this.top >= height - this.bottom) {
            this.top = height - this.bottom;
        }
    }
}

RectView.java

package com.example.sensor;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.View;

public class RectView extends View {
    Rect rect;
    private int width,height;
    Paint paint;
    public RectView(Context context, int width, int height) {
        super(context);
        this.width=width;
        this.height=height;
        paint =new Paint();
        paint.setColor(Color.GREEN);
        rect=new Rect(width,height);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawRect(rect.getLeft(),rect.getTop(),rect.getRight()+rect.getLeft(),rect.getTop()+rect.getBottom(),paint);
    }
}

值得注意的是为了满足不超出屏幕的需求,在构造的时候还传入了宽高两个属性(即屏幕的宽高)

Main2Activity
package com.example.sensor;

import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;

public class Main2Activity extends Activity {

    private RectView rv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        rv = new RectView(this, dm.widthPixels, dm.heightPixels);
        setContentView(rv);
        SensorManager sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        Sensor type_gravity = sm.getDefaultSensor(Sensor.TYPE_GRAVITY);
        sm.registerListener(new SensorEventListener() {
            @Override
            public void onSensorChanged(SensorEvent event) {
                float x = event.values[0];
                float y = event.values[1];
                rv.rect.setLeft(Math.round(x));
                rv.rect.setTop(Math.round(y));
                rv.invalidate();//屏幕重绘
            }

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

            }
        }, type_gravity, SensorManager.SENSOR_DELAY_GAME);
    }
}

效果

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

云无心鸟知还

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值