Android未将传感器中的数据保存在内部存储文件中

时间:2018-07-10 05:43:26

标签: java android save android-sensors

我现在正在做我的第一个android项目,包括在mainAcitivity调用后15分钟内将数据从手机上的传感器保存。考虑到有时手机中可能没有SD卡,我决定将文件存储在内部存储器中。

现在,我将这些问题困扰了几天:

  1. 保存数据后,我用getFilesDir()返回了目录,但是无论如何我都找不到显示的路由。 screen shot after running service /data/user/0/com.example.liya.medicinecalendar/files/201807100711.txt

  2. 有时,根据吐司的服务开始和结束的时间并不理想。

我刚刚使用过的MainActivity.class

startService(new Intent(MainActivity.this,SaveSensorService.class));

我没有创建线程是因为我不想让屏幕活动和服务同时运行。

这是我的SaveSensorService.class

public class SaveSensorService extends Service implements SensorEventListener {

    private static final String TAG = "SaveSensorService";

    private Float xValue, yValue, zValue, xGyroValue, yGyroValue, zGyroValue;
    SensorManager sensorManager;
    private Sensor accelerometer, mGyro;


    private SimpleDateFormat Date_Format,Newtime_Format;
    private  Calendar calendar;
    private String StartTime, StopTime, CurrentTime, FileName;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStartCommand: SaveSensorService started.");

        Newtime_Format = new SimpleDateFormat("HHmmss");
        calendar = Calendar.getInstance();
        StartTime = Newtime_Format.format(calendar.getTime());
        CurrentTime = StartTime;
        //calendar.add(Calendar.MINUTE, 15);//save sensor data for 15min
        calendar.add(Calendar.SECOND,60);//for test
        StopTime = Newtime_Format.format(calendar.getTime());
        Toast.makeText(SaveSensorService.this, StartTime+" SaveSensorService is running",Toast.LENGTH_SHORT).show();


        Log.d(TAG, "onCreate: Initializing Sensor Services");
        sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);

        accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        if (accelerometer != null) {
            sensorManager.registerListener(SaveSensorService.this, accelerometer, 5000000);
            Log.d(TAG, "onCreate: Registered accelerometer Listener");
        } else {
            xValue = null;
            yValue = null;
            zValue = null;
            ;
        }

        mGyro = sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
        if (mGyro != null) {
            sensorManager.registerListener(SaveSensorService.this, mGyro, 5000000);
            Log.d(TAG, "onCreate: Registered Gyro Listener");
        } else {
            xGyroValue = null;
            yGyroValue = null;
            zGyroValue = null;
        }

        if ((accelerometer!=null || mGyro != null)&&CurrentTime.compareTo(StopTime) < 0) {
            calendar = Calendar.getInstance();
            CurrentTime = Newtime_Format.format(calendar.getTime());
            saveSensor();
        }

        else  {
            stopSelf();
            Toast.makeText(SaveSensorService.this,"Time's up or device not support."+ CurrentTime,Toast.LENGTH_SHORT).show();

        }

        return START_STICKY;
    }



    @Override
    public void onDestroy() {
        Log.d(TAG, "onDestroy: SaveSensorService stopped.");
        Toast.makeText(SaveSensorService.this,"Sensordaten wurden gespeichert."+ CurrentTime,Toast.LENGTH_SHORT).show();
    }


    /*********** save the sensor data during the set time - START *******************/

        public void saveSensor () {

            //create a new file, named by the current time
            Date_Format = new SimpleDateFormat("yyyyMMddHHmm");
            FileName = Date_Format.format(calendar.getTime())+".txt";

            try{
            FileOutputStream fos = null;


                //to prevent that the file fail to be read or created, use catch to print the error
                // write in txt,

                fos = openFileOutput(FileName, MODE_APPEND);
                //write the first line - description
                fos.write("xValue\tyValue\tzValue\txGyroValue\tyGyroValue\tzGyroValue\r\n".getBytes()); //define the first line

                    //append the sensor data in the file
                    fos.write((xValue + "\t" + yValue + "\t" + zValue + "\t" + xGyroValue + "\t" + yGyroValue + "\t" + zGyroValue + "\r\n").getBytes());
                    fos.flush();
                    fos.close();
                } catch (FileNotFoundException e1) {
                e1.printStackTrace();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            Log.d(TAG, "onClick: file ist written.");
                Toast.makeText(this, "Saved to " + getFilesDir() + "/" + FileName, Toast.LENGTH_SHORT).show();

            }



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

    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
        Sensor sensor = sensorEvent.sensor;

        //get accelerometer data
        if(sensor.getType()==Sensor.TYPE_ACCELEROMETER) {
            Log.d(TAG, "onSensorChanged: X:" + sensorEvent.values[0] + "Y:" + sensorEvent.values[1] + "Z:" + sensorEvent.values[2]);

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

        }

        //put gyrocope data
        else if(sensor.getType()==Sensor.TYPE_GYROSCOPE) {
            Log.d(TAG, "onSensorChanged: XG:" + sensorEvent.values[0] + "YG:" + sensorEvent.values[1] + "ZG:" + sensorEvent.values[2]);

            xGyroValue = sensorEvent.values[0];
            yGyroValue = sensorEvent.values[1];
            zGyroValue = sensorEvent.values[2];

        }

    }

    /***************** save the sensor data during the set time - END *************************/

}

这是我的AndroidMainifest.xml

   <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.liya.medicinecalendar">
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>

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

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".CalendarActivity"></activity>
        <service android:name=".SaveSensorService"
        android:enabled="true"/>
        <receiver android:name=".AlarmReceiver"></receiver>
        <service android:name=".AlarmService"
            android:enabled="true"/>
    </application>

</manifest> 

如果有人可以在保存数据时给我一些解决该问题的建议,我将非常感激。提前非常感谢您!

0 个答案:

没有答案