用于显示和记录传感器数据的Android应用

时间:2014-10-15 22:33:57

标签: android

我是Android编程的新手,我正在尝试理解android程序中的控制流程。我一直致力于一个记录和显示传感器数据的程序。

public class MainActivity extends ActionBarActivity implements SensorEventListener

这是使用onCreate()btnStart.setOnClickListener(new OnClickListener(), btnStop.setOnClickListener(new OnClickListener(), onSensorChanged(SensorEvent event)执行大部分重要任务的主要课程。

onCreate()包含以下所有代码:

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    title = (TextView)findViewById(R.id.titleView);

    acc_x = (TextView)findViewById(R.id.acc_x_values);
    acc_y = (TextView)findViewById(R.id.acc_y_values);
    acc_z = (TextView)findViewById(R.id.acc_z_values);

    x = (TextView)findViewById(R.id.acc_x);
    y = (TextView)findViewById(R.id.acc_y);
    z = (TextView)findViewById(R.id.acc_z);

    btnStart = (Button)findViewById(R.id.button_start);
    btnStop = (Button)findViewById(R.id.button_stop);
    sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
    mAccel = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    sensorManager.registerListener(this,sensorManager.getDefaultSensor(sensorType), 20000);

这里定义了开始和停止按钮的功能。

        btnStart.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {

            startFlag = true;
            String storepath = Environment.getExternalStorageDirectory().getPath();
            System.out.println("Stored at" +storepath);   // /storage/sdcard
            Toast.makeText(getBaseContext(), "Started Recording Data and Storing at"+storepath, Toast.LENGTH_SHORT).show();
            try {
                myFile = new File(storepath + "/GaitApp/" + name.getText() + "_acc.csv");
                myFile.createNewFile();

                fOut = new FileOutputStream(myFile);
                myOutWriter = new OutputStreamWriter(fOut);
                myBufferedWriter = new BufferedWriter(myOutWriter);
                myPrintWriter = new PrintWriter(myBufferedWriter);

            } catch (Exception e) {
                Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
            } 
        } //onclick
    }); //startbutton

    btnStop.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            Toast.makeText(getBaseContext(), "Stopped Recording",Toast.LENGTH_SHORT).show();
            startFlag = false;
            try {
                fOut.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }// onClick
    }); // btnstopButton

onSensorChanged() is:



    public void onSensorChanged(SensorEvent event) {
        if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
            if(startFlag){

            float[] values = event.values;
            // Movement
            float x_float = values[0];
            float y_float = values[1];
            float z_float = values[2];

            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
            String currentDateandTime = sdf.format(new Date());

            long curTime = System.currentTimeMillis();

            if ((curTime - lastUpdate) > 20) {
                long diffTime = (curTime - lastUpdate);
                lastUpdate = curTime;

                x_float = event.values[0];
                y_float = event.values[1];
                z_float = event.values[2];


            acc_x.setText(Float.toString(x_float));
            acc_y.setText(Float.toString(y_float));
            acc_z.setText(Float.toString(z_float));

            String res=String.valueOf(currentDateandTime+", "+x_float)+", "+String.valueOf(y_float)+", "+String.valueOf(z_float+"\n");
            Log.d("test", res);

            for (int i = 0; i % 1 == 0; i++) {
                if (startFlag) {

                    try{
                    fOut = new FileOutputStream(myFile);
                    myOutWriter = new OutputStreamWriter(fOut);
                    myBufferedWriter = new BufferedWriter(myOutWriter);
                    myPrintWriter = new PrintWriter(myBufferedWriter);
                    myPrintWriter.append(curTime - lastUpdate + ", " + x_float + ", " + y_float + ", " + z_float+ "\n");


                    }
                    catch (IOException e){
                        System.out.println("Exception: "+e);
                    }

                  //myPrintWriter.write(curTime - lastUpdate + ", " + x_float + ", " + y_float + ", " + z_float+ "\n");
                } //startFlag is true

                else {  
                        try {
                            myOutWriter.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        try {
                            fOut.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        } // catch
                } // else
            } //for
         } // if -- time
       } // startFlag
      } //accelerometer -- sensor
      } // onSensorChanged

我正在尝试了解onSensorChanged()如何将控件和过程中的加速数据传输到onCreate()以显示和存储。

2 个答案:

答案 0 :(得分:0)

onCreate方法仅用于初始设置视图。必须通过故意调用它们来更新显示。此外,UI必须在UI线程上进行更新。由于onSensorChanged调用可以异步进行,如果您希望传感器更新触发显示更新,则必须向自己发送UI线程事件。一种选择是使用处理程序,例如以下未经测试的代码。

private Handler mHandler;

public void onCreate() {
    mHandler = new Handler();
}

@Override
public void onSensorChanged(SensorEvent event) {
    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
        saveData(event);
        final long currentTime = System.currentTimeMillis();
        if (isResumed() && currentTime > (lasttime + SOME_DELAY)) {
            lasttime = currentTime;
            handler.post(new Runnable() {
                @Override
                public void run() {
                    updateDisplay(event);
                }
            });
        }
    }
}

private void updateDisplay(SensorEvent event) {
    acc_x.setText(...);
    acc_y.setText(...);
    acc_z.setText(...);
    x.setText(...);
    y.setText(...);
    z.setText(...);
}

根据您的应用程序,您可能希望在服务中记录您的数据。

答案 1 :(得分:0)

onSensorChanged()是这种情况下的处理程序。此回调函数负责更新UI并写入文件。