0

我想开发一个应用程序

  1. 在外部存储中创建文件

2.点击开始按钮时将加速度计读数写入文件

3.单击停止按钮时停止写入

4.点击读取按钮读取文件内容

我不知道如何在外部存储中创建文件并将加速度计的读数存储在其中,然后从文件中读取值。

我在 MainACtivity.java 中尝试了以下代码

package com.example.startstopbuttonaccelerometerreading;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements SensorEventListener {

private SensorManager mSensorManager;
private Sensor mAccelerometer;
TextView title,tv,tv1,tv2;
RelativeLayout layout;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
  //get layout
    layout = (RelativeLayout) findViewById(R.id.relative);

    //get textviews
    title=(TextView)findViewById(R.id.name);   
    tv=(TextView)findViewById(R.id.xval);
    tv1=(TextView)findViewById(R.id.yval);
    tv2=(TextView)findViewById(R.id.zval);

    }


public void onStartClick(View view) {
    final SensorEventListener mySensorEventListener = new SensorEventListener() { 
        public void onSensorChanged(SensorEvent sensorEvent) {
        if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {


        float x = sensorEvent.values[0]; 
        float y = sensorEvent.values[1]; 
        float z = sensorEvent.values[2]; // TODO apply the acceleration changes to your application.
        textView.append("\nACC_x = "+ x + ", ACC_y = "+y+ ", ACC_z = " + z);
        acc+="\n"+x+ ", "+ y+","+z;

        try {
            File myFile = new File("/sdcard/acc.txt");
            myFile.createNewFile();
            FileOutputStream fOut = new FileOutputStream(myFile);
            OutputStreamWriter myOutWriter = 
                                    new OutputStreamWriter(fOut);
            myOutWriter.append(acc);
            myOutWriter.close();
            fOut.close();
            Toast.makeText(getBaseContext(),
                    "Done writing SD 'acc.txt'",
                    Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Toast.makeText(getBaseContext(), e.getMessage(),
                    Toast.LENGTH_SHORT).show();
        }

        }
    }
        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {
            // TODO Auto-generated method stub

        }
    };
    // write on SD card file data in the text box 
    int sensorType = Sensor.TYPE_ACCELEROMETER; 
    mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);

}// onClick
;


public void onStopClick(View view) {
    mSensorManager.unregisterListener(this);
}


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

}



}

这是 activity_main.xml 代码:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity"
    android:id="@+id/relative" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="40dp"
        android:layout_marginTop="124dp"
        android:text="Start"
        android:onClick="onStartClick" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/button1"
        android:layout_marginLeft="37dp"
        android:layout_toRightOf="@+id/button1"
        android:text="Stop"
        android:onClick="onStopClick" />
    <TextView
    android:textSize="30dp"
    android:id="@+id/name"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    />

   <TextView
    android:textSize="20dp"
    android:layout_below="@+id/name"
    android:id="@+id/xval"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    />

    <TextView
    android:textSize="20dp"
    android:id="@+id/yval"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/xval"
    />

    <TextView
    android:textSize="20dp"
    android:id="@+id/zval"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/yval"
    />

</RelativeLayout>

我在 androidmanifest.xml 中写了权限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

MainActivity 没有被编译。错误是 acc 和 textview 无法解决。我想知道在外部存储中创建文件并向其中写入加速度计读数并从文件中读取数据的代码。

4

2 回答 2

1

我已将您的代码重写为以下内容,包括 AndroidManifest.xml、activity_main.xml 和 MainActivity.java。

该程序中有三个按钮。

1.Start:开始将三轴数据写入acc.txt。

2.Stop:停止写入数据。

3.Read:读取acc.txt中的所有数据

我创建了一个编辑文本以在单击“阅读”按钮后显示 acc.txt 中的内容。这个程序有一些延迟时间。您可以自行调整。

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.so_problem"
    android:versionCode="1"
    android:versionName="1.0" >
    
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/> 
    
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.so_problem.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

activity_main.xml

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity"
    android:id="@+id/relative" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="40dp"
        android:layout_marginTop="124dp"
        android:text="Start"
        android:onClick="onStartClick" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/button1"
        android:layout_marginLeft="37dp"
        android:layout_toRightOf="@+id/button1"
        android:text="Stop"
        android:onClick="onStopClick" />
    
     <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button1"
        android:layout_alignRight="@+id/button2"
        android:layout_centerVertical="true"
        android:text="Read"
        android:onClick="onReadClick" />
     
    <TextView
        android:id="@+id/name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textSize="30dp" />

   <TextView
        android:textSize="20dp"
        android:layout_below="@+id/name"
        android:id="@+id/xval"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:textSize="20dp"
        android:id="@+id/yval"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/xval" />

    <TextView
        android:textSize="20dp"
    android:id="@+id/zval"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/yval" />

    <EditText
        android:id="@+id/showval"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/zval"
        android:layout_alignRight="@+id/zval"
        android:layout_below="@+id/button3"
        android:layout_marginTop="18dp"
        android:clickable="false"
        android:cursorVisible="false"
        android:editable="false"
        android:ems="10"
        android:freezesText="true"
        android:inputType="none"
        android:lines="8"
        android:maxLines="1000"
        android:scrollbars="vertical"
        android:singleLine="false" />

</RelativeLayout>

MainActivity.java

package com.example.so_problem;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

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.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements SensorEventListener 
{

    private SensorManager mSensorManager;
    private Sensor mAccelerometer;
    TextView title,tvx,tvy,tvz;
    EditText etshowval;
    RelativeLayout layout;
    private String acc;
    private String read_str = "";
    private final String filepath = "/mnt/sdcard/acc.txt";
    private BufferedWriter mBufferedWriter;
    private BufferedReader mBufferedReader;
    private float x;
    private float y;
    private float z;
    
    public static final int MSG_DONE = 1;
    public static final int MSG_ERROR = 2;
    public static final int MSG_STOP = 3;
    
    private boolean mrunning;
    private Handler mHandler;
    private HandlerThread mHandlerThread;
    
    private Handler uiHandler = new Handler(){
        public void handleMessage(Message msg){ 
            String str = (String) msg.obj;
            switch (msg.what)
            {
                case MSG_DONE:
                    Toast.makeText(getBaseContext(), str,
                            Toast.LENGTH_SHORT).show();
                    break;
                case MSG_ERROR: 
                    Toast.makeText(getBaseContext(),str,
                            Toast.LENGTH_SHORT).show();
                    break;
                case MSG_STOP:
                    Toast.makeText(getBaseContext(), str,
                            Toast.LENGTH_SHORT).show();
                default:
                    break;
            }
            super.handleMessage(msg);
        }
    };

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
      //get layout
        layout = (RelativeLayout) findViewById(R.id.relative);
    
        //get textviews
        title = (TextView)findViewById(R.id.name);   
        tvx = (TextView)findViewById(R.id.xval);
        tvy = (TextView)findViewById(R.id.yval);
        tvz = (TextView)findViewById(R.id.zval);
        etshowval = (EditText)findViewById(R.id.showval);
        title.setText("Accelerator");
                
        mHandlerThread = new HandlerThread("Working Thread");
        mHandlerThread.start();
        
        mHandler = new Handler(mHandlerThread.getLooper());
        mHandler.post(r);
    }
    
    private Runnable r = new Runnable(){
        @Override
        public void run ()
        {
            while(true)
            {
                if (mrunning)
                {
                    Message msg1 = new Message();
                    try 
                    {
                        WriteFile(filepath,acc);
                        msg1.what = MSG_DONE;
                        msg1.obj = "Start to write to SD 'acc.txt'";
                    } 
                    catch (Exception e) 
                    {
                        msg1.what = MSG_ERROR;
                        msg1.obj = e.getMessage();
                    }
                    uiHandler.sendMessage(msg1);
                }
                else
                {   
                    Message msg2 = new Message();
                    msg2.what = MSG_STOP;
                    msg2.obj = "Stop to write to SD 'acc.txt'";
                    uiHandler.sendMessage(msg2);
                }
                
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    };

    public void onStartClick(View view) 
    {
        start();
    }

    public void onStopClick(View view) 
    {
        stop();
    }
    
    public void onReadClick(View view) 
    {
        etshowval.setText(ReadFile(filepath));
    }
    
    private synchronized void start()
    {
        mrunning = true;
    }
    
    private synchronized void stop()
    {
        mrunning = false;
    }

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

    @Override
    public void onSensorChanged(SensorEvent sensorEvent) 
    {
        // TODO Auto-generated method stub
    
        if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER) 
        {
            x = sensorEvent.values[0]; 
            y = sensorEvent.values[1]; 
            z = sensorEvent.values[2]; 
            acc= String.valueOf(x) + ", " + String.valueOf(y) + ", " + String.valueOf(z);
            
            tvx.setText("X = "+ String.valueOf(x));
            tvy.setText("Y = "+ String.valueOf(y));
            tvz.setText("Z = "+ String.valueOf(z));
        }
    }

    public void CreateFile(String path)
    {
        File f = new File(path);
        try {
            Log.d("ACTIVITY", "Create a File.");
            f.createNewFile();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    public String ReadFile (String filepath)
    {
        mBufferedReader = null;
        String tmp = null;
        
        if (!FileIsExist(filepath))
            CreateFile(filepath);
        
        try 
        {
            mBufferedReader = new BufferedReader(new FileReader(filepath));
            // Read string
            while ((tmp = mBufferedReader.readLine()) != null) 
            {
                tmp += "\n";
                read_str += tmp;
            }
        } 
        catch (IOException e) 
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return read_str;
    }
    
    public void WriteFile(String filepath, String str)
    {
        mBufferedWriter = null;
        
        if (!FileIsExist(filepath))
            CreateFile(filepath);
        
        try 
        {
            mBufferedWriter = new BufferedWriter(new FileWriter(filepath, true));
            mBufferedWriter.write(str);
            mBufferedWriter.newLine();
            mBufferedWriter.flush();
            mBufferedWriter.close();
        }
        catch (IOException e) 
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    public boolean FileIsExist(String filepath)
    {
        File f = new File(filepath);
        
        if (! f.exists())
        {
            Log.e("ACTIVITY", "File does not exist.");
            return false;
        }
        else
            return true;
    }
    
    @Override
    protected void onPause()
    {
    // TODO Auto-generated method stub
        mSensorManager.unregisterListener(this);
        Toast.makeText(this, "Unregister accelerometerListener", Toast.LENGTH_LONG).show();
        super.onPause();
    } 
}
于 2014-01-03T07:30:49.160 回答
0
 textView.append("\nACC_x = "+ x + ", ACC_y = "+y+ ", ACC_z = " + z);
acc+="\n"+x+ ", "+ y+","+z;

您没有在任何地方声明“textView”或“acc”变量

即使在解决了这个问题之后,您上面提供的代码示例也会以仅包含最近的传感器事件记录的文件结束。因为它会在每次发生传感器事件时创建一个新文件,将测量值写入其中,然后关闭它。当提供新的测量值时,将使用相同的名称创建一个新文件,因此将删除旧条目。

执行该任务的良好做法可能如下:

  1. 将文件流作为私有变量存储在您的活动中
  2. 在开始按钮的单击事件处理程序中,打开文件或创建它(如果不存在).. 并将其流存储到您的活动的私有变量中..还将侦听器注册到加速度计传感器事件。

  3. 在 onSensorChanged 事件中,将新测量值附加到文件流

  4. 在停止按钮的单击事件处理程序中,取消注册lisetener,并关闭文件流。
于 2013-06-07T11:19:56.313 回答