2014-10-15 2 views
0

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); 

그리고 시작 및 정지 버튼 funtionalities 여기에 정의되어 있습니다.

 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()에 가속도 데이터를 표시하고 저장하는 방법을 이해하기 위해 노력하고있어.

답변

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(...); 
} 

응용 프로그램에 따라 서비스에 데이터를 기록 할 수 있습니다.

0

onSensorChanged()는이 경우 처리기입니다. 이 콜백 함수는 UI를 업데이트하고 파일에 쓰는 것을 담당합니다.

관련 문제