Andoid Studio-android development 05-Get the acceleration sensor data and store it in a file

This article introduces how to obtain acceleration data and store it in a csv file

1. The desired effect

 

Features:

1. When you click the start button, start the acceleration sensor, read the data, display it on the screen, and store it in the List ;

2. Click the stop button to stop the accelerometer and save the data in the List into a csv file .

Knowledge points:

1. How does one activity implement two interfaces

2. How to obtain sensor service, register service, and cancel service

3. How to get the handle of button and textview for operation

4. How to associate the click event of a button

Second, the activity file

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">


    <TextView
        android:id="@+id/tvx"
        android:layout_width="214dp"
        android:layout_height="69dp"
        android:text="TextView"
        tools:layout_editor_absoluteX="117dp"
        tools:layout_editor_absoluteY="100dp" />

    <TextView
        android:id="@+id/tvy"
        android:layout_width="214dp"
        android:layout_height="53dp"
        android:text="TextView"
        tools:layout_editor_absoluteX="126dp"
        tools:layout_editor_absoluteY="158dp" />

    <TextView
        android:id="@+id/tvz"
        android:layout_width="214dp"
        android:layout_height="53dp"
        android:text="TextView"
        tools:layout_editor_absoluteX="130dp"
        tools:layout_editor_absoluteY="234dp" />

    <Button
        android:id="@+id/bt_dsp"
        android:layout_width="131dp"
        android:layout_height="79dp"
        android:text="开始显示加速度"
        tools:layout_editor_absoluteX="115dp"
        tools:layout_editor_absoluteY="444dp" />

    <Button
        android:id="@+id/bt_stop"
        android:layout_width="217dp"
        android:layout_height="81dp"
        android:text="停止显示加速度" />

</LinearLayout>

Three, java code file 

package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Environment;
import android.content.Context;
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 java.text.SimpleDateFormat;
import java.util.Date;


import android.util.Log;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Scanner;
import  java.util.List;


public class MainActivity extends AppCompatActivity implements SensorEventListener,View.OnClickListener {

    private SensorManager mSensorMgr;
    private  TextView tvx;
    private  TextView tvy;
    private  TextView tvz;
    private  List<String> LS;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        LS=new ArrayList<String>();

        Button bt=findViewById(R.id.bt_dsp);
        bt.setOnClickListener(this);

        Button bt_stop=findViewById(R.id.bt_stop);
        bt_stop.setOnClickListener(this);

        tvx=findViewById(R.id.tvx);
        tvy=findViewById(R.id.tvy);
        tvz=findViewById(R.id.tvz);
        //
        mSensorMgr=(SensorManager)getSystemService(Context.SENSOR_SERVICE);
    }

    protected void onPause()
    {
        super.onPause();
        mSensorMgr.unregisterListener(this);
    }

    protected void onResume()
    {
        super.onResume();
    }
    protected void onStop()
    {
        super.onStop();
        mSensorMgr.unregisterListener(this);

    }
    public void onSensorChanged(SensorEvent event)
    {
        if(event.sensor.getType()==Sensor.TYPE_ACCELEROMETER)
        {
            float[] values=event.values;

            tvx.setText("ACC_X: "+Float.toString(values[0]));
            tvy.setText("ACC_Y: "+Float.toString(values[1]));
            tvz.setText("ACC_Z: "+Float.toString(values[2]));

            Date date=new Date();
            SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time=formatter.format(date);
            String s="";
            s=time+" "+Float.toString(values[0])+" "+Float.toString(values[1])+" "+Float.toString(values[2])+"\n";
            LS.add(s);

        }
    }

    public void onAccuracyChanged(Sensor sensor,int accuracy)
    {//不用处理,空着就行
        return;
    }





    private static final String TAG = "ACCCollection:";

    public static void writeLS(List<String> LS) {
        try {
            String path=Environment.getExternalStorageDirectory().getAbsolutePath()+"/aaa/";
            File folde=new File(path);
            //tvx.setText(path);
            Log.i(TAG, "write: -------1");
            if (!folde.exists() || !folde.isDirectory())
            {
                Log.i(TAG, "write: --------2");
                folde.mkdirs();
            }
            File file=new File(path,"aa.csv");
            if(!file.exists())
            {
                file.createNewFile();
            }

            BufferedWriter bw = new BufferedWriter(new FileWriter(file, true));
            int i;
            for(i=0;i<LS.size();i++)
            {
                bw.write(LS.get(i));;
                bw.newLine();// 行换行
            }
            bw.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }



    public void onClick(View v)
    {
         if(v.getId()==R.id.bt_dsp)
         {
             mSensorMgr.unregisterListener(this,mSensorMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER));
             mSensorMgr.registerListener(this,
                     mSensorMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
                     SensorManager.SENSOR_DELAY_NORMAL);
             LS.clear();
             return;
         }
         if(v.getId()==R.id.bt_stop)
         {
             mSensorMgr.unregisterListener(this);

             writeLS(LS);

             return;
         }
    }
}

Guess you like

Origin blog.csdn.net/weixin_43917370/article/details/107967650