2013-01-15 80 views
1

我寫了下面的線來記錄與一個按鈕一個文件加速計數據點擊與按鈕停止錄製加速度計數據點擊

startButton.setOnClickListener(new OnClickListener() { 

     public void onClick(View v) { 


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


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

       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 
      sm = (SensorManager)getSystemService(Context.SENSOR_SERVICE); 
      int sensorType = Sensor.TYPE_ACCELEROMETER; 
      sm.registerListener(mySensorEventListener,sm.getDefaultSensor(sensorType), SensorManager.SENSOR_DELAY_NORMAL); 

     }// onClick 
     }); 

現在我希望它停止與另一個按鈕點擊記錄數據。例如 -

stopButton.setOnClickListener(new OnClickListener() { 

    public void onClick(View v) { 
     int sensorType = Sensor.TYPE_ACCELEROMETER; 
     sm.unregisterListener(listener, sensor) 
    }// onClick 
    }); // btnstopButton 
} 

想要使用unregisterListener,但大多數情況下它是不贊成使用的。

任何人都可以幫忙嗎?

回答

2

我想你要聲明你的SensorEventListener對象的onClick()方法之外,因此您可以在其他的onClick註銷它()方法:

sm.unregisterListener(mySensorEventListener, sensorType); 

這就是方法簽名,你要根據使用docs

3

documentation表示使用與SensorListener關聯的方法已被棄用,並且使用SensorEventListener代替。你的代碼片段不應該拋出過時的警告,但是如果你使用SensorListener,它會。