在好例子网,分享、交流、成长!
您当前所在位置:首页Java 开发实例Android平台开发 → android传感器 实例源码

android传感器 实例源码

Android平台开发

下载此实例
  • 开发语言:Java
  • 实例大小:0.69M
  • 下载次数:24
  • 浏览次数:207
  • 发布时间:2019-12-03
  • 实例类别:Android平台开发
  • 发 布 人:战羡
  • 文件格式:.zip
  • 所需积分:2
 相关标签: 传感器

实例介绍

【实例简介】

【实例截图】

from clipboard

【核心代码】


package edu.lsnu.scope;

import android.content.Context;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Bundle;

import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    //sensorManager instance used to create Sensor_Manager's
    SensorManager sensorManager;
    //linegraphview for displaying accelerometer data
    LineGraphView graph;
    //List of each sensor manager (each one responsible for handling a different sensor)
    LinkedList<Sensor_Manager> managers;
    //clear readings button
    int btn_clear = 1;
    //record last 100 readings button
    int btn_record = 2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //setup the UI and initialize sensor event managers
        doInitialize();
    }

    private void doInitialize() {
        //initialize the sensorManager
        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);

        //add UI controls and event handlers for sensors
        doInitializeSensors();

    }


    private void doInitializeSensors() {
        //get a reference to the linearlayout
        LinearLayout linlayout = (LinearLayout) findViewById(R.id.LinearLayoutDisplay);
        //create a new graph instance with the specified withd and height
        graph = new LineGraphView(getApplicationContext(), 100, Arrays.asList("x", "y", "z"), 1020, 600);
        graph.setVisibility(View.VISIBLE);
        //add teh graph to teh linearlayout
        linlayout.addView(graph);

        //create button for clearing min/max readings
        Button btn_clearMinMax = new Button(getApplicationContext());
        btn_clearMinMax.setText("Clear Historical Min/Max");
        btn_clearMinMax.setOnClickListener(this);
        //set the id of the button so we can refer to it later
        btn_clearMinMax.setId(btn_clear);
        linlayout.addView(btn_clearMinMax);

        //create button for recording last 100 readins of accelerometer
        Button btn_Recordvalues = new Button(getApplicationContext());
        btn_Recordvalues.setText("Record last 100 readings");
        btn_Recordvalues.setOnClickListener(this);
        //set the id of the button so we can refer to it later
        btn_Recordvalues.setId(btn_record);
        linlayout.addView(btn_Recordvalues);

        //List of sensor types that we want to create a Sensor_Manger for
        List<Sensor> SensorsToUse = new LinkedList<Sensor>();
        managers = new LinkedList<Sensor_Manager>();
        //add the 5 types of sensors
        SensorsToUse.add(sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER));
        SensorsToUse.add(sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT));
        SensorsToUse.add(sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD));
        SensorsToUse.add(sensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR));
        SensorsToUse.add(sensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION));

        //create and initialize displays and handlers for each sensor
        for (Sensor s : SensorsToUse) {
            //create the textview for displaying realtime values
            TextView tv = new TextView(getApplicationContext());
            //create the textview for displaying min/mas values
            TextView tvm = new TextView(getApplicationContext());
            //set the text color and initialize the textview to a default message
            tv.setTextColor(Color.BLUE);
            tv.setText("No Sensor Present");
            tvm.setTextColor(Color.BLUE);
            tvm.setText("No Sensor Present");
            //add the textviews to the linearlayout
            linlayout.addView(tv);
            linlayout.addView(tvm);
            //create a new Sensor_Manager instance for the sensor
            Sensor_Manager sm = new Sensor_Manager(tv, tvm, graph);
            //if accelerometer we are initializing set its update speed to GAME_DELAY
            if (s == sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)) {
                sensorManager.registerListener(sm, s, SensorManager.SENSOR_DELAY_GAME);
            } else {
                sensorManager.registerListener(sm, s, SensorManager.SENSOR_DELAY_NORMAL);
            }
            //add this manager to our list of Sensor_Managers so we can refer to it later
            managers.add(sm);
        }

    }

    //write the last 100 readings to a .csv file
    private int recordData() {
        //initialize the printwriter
        PrintWriter writer = null;
        try {

            //create the filepath for our output file
            File path = new File(getExternalFilesDir("Recorded Data"), "AccelerometerReadings.csv");

            //open the file
            FileOutputStream sData = new FileOutputStream(path);
            OutputStreamWriter myOutWriter = new OutputStreamWriter(sData);
            BufferedWriter myBufferedWriter = new BufferedWriter(myOutWriter);
            writer = new PrintWriter(myBufferedWriter);


            //get the values to record
            float[][] values = managers.get(0).collectHistory();

            //write headings for columns
            writer.println("X,Y,Z");
            //write comma delimited values
            for (int i = 0; i < 100; i  ) {
                //write the values to the debug log for faster access to the values (during debugging)
                Log.d("Data", String.format("%f,%f,%f", values[0][i], values[1][i], values[2][i]));
                //write the values to the file
                writer.println(String.format("%f,%f,%f", values[0][i], values[1][i], values[2][i]));
            }

            //close the printwriter
            writer.close();


        } catch (IOException ex) {
            //log any errors
            Log.e("ERROR WRITING TO FILE", ex.toString());
            //failed to write values
            return -1;
        } finally {
            //ensure the file is closed when done
            if (writer != null) {
                writer.close();
            }
        }
        //values successfully written
        return 0;
    }


    @Override
    //handle button clicks
    public void onClick(View v) {
        //was the clear min/max values button
        if (v.getId() == btn_clear) {
            Context clearContext = getApplicationContext();
            //display message to user that the values were cleared
            CharSequence clearText = "Cleared all maximum/minimum values!";
            int clearDuration = Toast.LENGTH_SHORT;

            Toast.makeText(clearContext, clearText, clearDuration).show();

            //clear all the sensors min/max values
            for (Sensor_Manager sm : managers) {
                sm.ClearMinMax();
            }
        }
        //was the record last 100 values button
        else if (v.getId() == btn_record) {
            //record data - store the result of the write opperation in recorded (0 = written, -1 = failed to write)
            int recorded = recordData();

            Context historyContext = getApplicationContext();
            //display message to user that the values were recorded
            CharSequence historyText = "Recorded last 100 accelerometer values!";
            CharSequence historyTextFailed = "FAILED to Record last 100 accelerometer values!";
            int historyDuration = Toast.LENGTH_SHORT;

            //display message to user
            if (recorded == 0) {
                Toast.makeText(historyContext, historyText, historyDuration).show();
            } else {
                Toast.makeText(historyContext, historyTextFailed, historyDuration).show();
            }


        }
    }
}


标签: 传感器

实例下载地址

android传感器 实例源码

不能下载?内容有错? 点击这里报错 + 投诉 + 提问

好例子网口号:伸出你的我的手 — 分享

网友评论

发表评论

(您的评论需要经过审核才能显示)

查看所有0条评论>>

小贴士

感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。

  • 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
  • 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
  • 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
  • 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。

关于好例子网

本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明

;
报警