[問題] 資料存取 儲存txt檔於內部記憶體

作者: pisces1026 (pisces1026)   2015-07-08 10:35:20
大家好 目前剛開始學習android
由於之前也沒接觸過java
可能有很多不懂的地方請大家多多包涵
目前我要寫一個收感測器的值儲存在一個txt檔
感測器部分已經寫好 在檔案處理部分一直無法完成
在MainActivity中的onCreate我想寫建檔跟把值存進去
於是寫了一個按鈕,按下後開始將accelerometer的xyz值存入txt
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button = (Button)this.findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
FileOutputStream fos = null;
try{
fos = openFileOutput("test.txt" , Context.MODE_APPEND );
fos.write(value.getBytes());
}catch(IOException e) {
Log.e("InternalStorageEx", e.toString());
}
}
});
sm = (SensorManager) getSystemService(SENSOR_SERVICE);
acc_x_View = (TextView) findViewById(R.id.acc_x);
acc_y_View = (TextView) findViewById(R.id.acc_y);
acc_z_View = (TextView) findViewById(R.id.acc_z);
}//end onCreate
然後在收加速度計值的部分
private SensorEventListener acc_listener = new SensorEventListener()
{
public void onAccuracyChanged(Sensor sensor, int accuracy) {
getType());
if(sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD)
{
}
}
public void onSensorChanged(SensorEvent event) {
if(event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {//sensors.get(0)
acc_x_View.setText("Mag X : " + (float) event.values[0]);
acc_y_View.setText("Mag Y : " + (float) event.values[1]);
acc_z_View.setText("Mag Z : " + (float) event.values[2]);
}
}
};
雖然還沒寫好 但有幾個問題想問大家
1.這樣寫應該可以建出txt檔在手機內部儲存空間吧(因為沒SD卡所以存在內部)
但是我到手機內android/data/資料夾內沒有看到我package資料夾
所以我也找不到是否有成功建立txt檔
2.因為onSensorChanged會在sensor值改變時啟動
我不曉得要如何寫write
應該寫在onSensorChanged內還是onCreate內?
(我的目的是 按下按鈕開始儲存sensor的值,
例如可能是10秒鐘內的sensor值)
因為還剛在學習有很多不懂
還請大家多多包涵
謝謝!!
作者: mshockwave (夏克維夫)   2015-07-08 11:54:00
1. 你有root嗎?沒有的話看不到txt2. onSensorChange 資料流量很恐怖,這樣每次有資料就寫檔IO會爆掉
作者: cuda (Cuda)   2015-07-13 11:38:00
getExternalFilesDir 用法 http://goo.gl/ogCOj0 可以放在這這樣就可以看得見你的檔案了2. onCreate在Activity lifecycle只會起來一次 不符合你需求在onSensorChanged先弄個變數cached住資料, 按下按鈕再寫檔另外寫檔因為是IO 建議寫在non UI thread

Links booklink

Contact Us: admin [ a t ] ucptt.com