安卓手机传感器采集数据并保存数据

1.layout布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <TextView
        android:id="@+id/TextView0"
        android:layout_width="fill_parent"
        android:layout_height="180dp"
        android:gravity="center" />
    <TextView
        android:id="@+id/myTime"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center" />
    <TextView
        android:id="@+id/accelerateX"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center" />
    <TextView
        android:id="@+id/accelerateY"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center" />
    <TextView
        android:id="@+id/accelerateZ"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center" />

    <TextView
        android:id="@+id/angulX"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center" />
    <TextView
        android:id="@+id/angulY"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center" />
    <TextView
        android:id="@+id/angulZ"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center" />

    <TextView
        android:id="@+id/orientationX"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center" />
    <TextView
        android:id="@+id/orientationY"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center" />
    <TextView
        android:id="@+id/orientationZ"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center" />
    <Button
        android:id="@+id/addData_start"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="START"/>
    <Button
        android:id="@+id/addData_end"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="END"/>
    <Button
        android:id="@+id/clear"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="CLEAR" />

</LinearLayout>

2.AndroidManifest.xml文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.sensorapplication">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.SensorApplication">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

3.MainActivity类

package com.example.sensorapplication;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
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.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends Activity{

    private TextView time;
    private TextView accelerateX;
    private TextView accelerateY;
    private TextView accelerateZ;

    private TextView angulX;
    private TextView angulY;
    private TextView angulZ;

    private TextView orientationX;
    private TextView orientationY;
    private TextView orientationZ;

    private SensorManager sensorManager;
    private MyDatabaseHelper dbHelper;
    public boolean isRecord;

    public String time_value;
    public float accelerateX_value;
    public float accelerateY_value;
    public float accelerateZ_value;
    public float angulX_value;
    public float angulY_value;
    public float angulZ_value;
    public float orientationX_value;
    public float orientationY_value;
    public float orientationZ_value;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        accelerateX = (TextView) findViewById(R.id.accelerateX);
        accelerateY = (TextView) findViewById(R.id.accelerateY);
        accelerateZ = (TextView) findViewById(R.id.accelerateZ);

        angulX = (TextView) findViewById(R.id.angulX);
        angulY = (TextView) findViewById(R.id.angulY);
        angulZ = (TextView) findViewById(R.id.angulZ);

        orientationX = (TextView) findViewById(R.id.orientationX);
        orientationY = (TextView) findViewById(R.id.orientationY);
        orientationZ = (TextView) findViewById(R.id.orientationZ);

        //获取传感器管理对象
        sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        //获取传感器类型,三个传感器分别为加速度传感器、方向传感器、角速度传感器
        Sensor sensor1 = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        Sensor sensor2 = sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
        Sensor sensor3 = sensorManager.getDefaultSensor(Sensor.TYPE_GAME_ROTATION_VECTOR);
        //注册传感器监听器
        sensorManager.registerListener(listener1, sensor1, SensorManager.SENSOR_DELAY_GAME);
        sensorManager.registerListener(listener2, sensor2, SensorManager.SENSOR_DELAY_GAME);
        sensorManager.registerListener(listener3, sensor3, SensorManager.SENSOR_DELAY_GAME);

        addData();
    }

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

    private SensorEventListener listener1 = new SensorEventListener() {
        @Override
        public void onSensorChanged(SensorEvent event) {

            getTime(); //时间相关,放在这里调用保证时间更新

            float xValue = event.values[0];
            float yValue = event.values[1];
            float zValue = event.values[2];

            accelerateX.setText("加速度X: " + xValue);
            accelerateY.setText("加速度Y: " + yValue);
            accelerateZ.setText("加速度Z: " + zValue);

            accelerateX_value = xValue;
            accelerateY_value = yValue;
            accelerateZ_value = zValue;
        }

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

    private SensorEventListener listener2 = new SensorEventListener() {
        @Override
        public void onSensorChanged(SensorEvent event) {
            float xValue = event.values[0];
            float yValue = event.values[1];
            float zValue = event.values[2];

            angulX.setText("角速度X: " + xValue);
            angulY.setText("角速度Y: " + yValue);
            angulZ.setText("角速度Z: " + zValue);

            angulX_value = xValue;
            angulY_value = yValue;
            angulZ_value = zValue;
        }

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

    private SensorEventListener listener3 = new SensorEventListener() {
        @Override
        public void onSensorChanged(SensorEvent event) {
            float xValue = event.values[0];
            float yValue = event.values[1];
            float zValue = event.values[2];

            orientationX.setText("方向X: " + xValue);
            orientationY.setText("方向Y: " + yValue);
            orientationZ.setText("方向Z: " + zValue);

            orientationX_value = xValue;
            orientationY_value = yValue;
            orientationZ_value = zValue;
        }

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

    //时间相关方法
    private void getTime() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日   HH:mm:ss.SSS");
        Date mDate = new Date(System.currentTimeMillis());
        String myTime = formatter.format(mDate);
        time = (TextView) findViewById(R.id.myTime);
        time.setText("当前时间:" + myTime);
        time_value = formatter.format(mDate);
    }

    //添加数据方法
    private void addData() {
        dbHelper = new MyDatabaseHelper(this, "SQLite1.db", null, 1);
        dbHelper.getWritableDatabase();
        Button start = (Button) findViewById(R.id.addData_start);
        Button end = (Button) findViewById(R.id.addData_end);
        Button clear = (Button) findViewById(R.id.clear);
        start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "开始保存", Toast.LENGTH_SHORT).show();
                isRecord = true;
                if (isRecord = true) {
                    Timer timer = new Timer();
                    timer.schedule(new TimerTask() {
                        @Override
                        public void run() {
                            SQLiteDatabase db = dbHelper.getWritableDatabase();
                            ContentValues values = new ContentValues();
                            values.put("time", time_value);
                            values.put("accelerateX", accelerateX_value);
                            values.put("accelerateY", accelerateY_value);
                            values.put("accelerateZ", accelerateZ_value);
                            values.put("angulX", angulX_value);
                            values.put("angulY", angulY_value);
                            values.put("angulZ", angulZ_value);
                            values.put("orientationX", orientationX_value);
                            values.put("orientationY", orientationY_value);
                            values.put("orientationZ", orientationZ_value);
                            db.insert("Sensor1", null, values);
                        }
                    }, 0, 200);
                }
            }
        });
        end.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isRecord = false;
                Toast.makeText(MainActivity.this, "结束保存", Toast.LENGTH_SHORT).show();
            }
        });
        clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SQLiteDatabase db = dbHelper.getWritableDatabase();
                db.delete("Sensor1", "id > ?", new String[]{"0"});
                Toast.makeText(MainActivity.this, "清除完成", Toast.LENGTH_SHORT).show();
            }
        });
    }

}



4.MyDatabaseHelper类

package com.example.sensorapplication;


import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;

public class MyDatabaseHelper extends SQLiteOpenHelper {
    public static final String CREATE_BOOK = "create table Sensor1("
            + "id integer primary key autoincrement,"
            + "time text,"
            + "accelerateX real,"
            + "accelerateY real,"
            + "accelerateZ real,"
            + "angulX real,"
            + "angulY real,"
            + "angulZ real,"
            + "orientationX real,"
            + "orientationY real,"
            + "orientationZ real)";
    private Context mContext;

    public MyDatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
        mContext = context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_BOOK);
        Toast.makeText(mContext, "Create succeeded", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}


  • 5
    点赞
  • 40
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
获取传感器数据并展示的步骤如下: 1. 在 AndroidManifest.xml 文件中添加相应的权限: ``` <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.READ_PHONE_STATE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.CAMERA" /> <uses-permission android:name="android.permission.RECORD_AUDIO" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> <uses-permission android:name="android.permission.BODY_SENSORS" /> ``` 2. 在 MainActivity.java 文件中创建 SensorManager 对象,并注册需要监听的传感器: ``` SensorManager sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); Sensor accelerometerSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); sensorManager.registerListener(this, accelerometerSensor, SensorManager.SENSOR_DELAY_NORMAL); ``` 3. 实现 SensorEventListener 接口,重写 onSensorChanged() 方法以获取传感器数据: ``` @Override public void onSensorChanged(SensorEvent event) { float[] values = event.values; switch (event.sensor.getType()) { case Sensor.TYPE_ACCELEROMETER: // 处理加速度传感器数据 break; case Sensor.TYPE_GYROSCOPE: // 处理陀螺仪传感器数据 break; case Sensor.TYPE_MAGNETIC_FIELD: // 处理磁场传感器数据 break; // 其他传感器类型同理 } } ``` 4. 在 UI 界面上展示传感器数据。 ``` // 示例代码展示加速度传感器数据 TextView xTextView = findViewById(R.id.xTextView); TextView yTextView = findViewById(R.id.yTextView); TextView zTextView = findViewById(R.id.zTextView); @Override public void onSensorChanged(SensorEvent event) { float[] values = event.values; switch (event.sensor.getType()) { case Sensor.TYPE_ACCELEROMETER: float x = values[0]; float y = values[1]; float z = values[2]; xTextView.setText(String.format("%.2f", x)); yTextView.setText(String.format("%.2f", y)); zTextView.setText(String.format("%.2f", z)); break; // 其他传感器类型同理 } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值