我尝试使用以下代码将一些数据写入Android(target = android-21)onTouch事件方法中的文本文件中:
package com.example.androidwritetxtfile;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView textview1;
String mRootDir;
File mTemptempDir;
File mTxtFile;
PrintWriter pw;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textview1 = (TextView) findViewById(R.id.textview1);
textview1.setText("AndroidWriteTxtFile");
mRootDir = Environment.getExternalStorageDirectory().toString();
mTemptempDir = new File(mRootDir + "/temptemp");
mTxtFile = new File(mTemptempDir, "AndroidWriteTxtFile.txt");
textview1.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
pw.println("Here onTouch()");
pw.flush();
return true;
}
});
}
@Override
protected void onResume() {
super.onResume();
try {
pw = new PrintWriter(mTxtFile, "UTF-8");
pw.println("This is a testing from AndroidWriteTxtFile");
pw.println("Here onResume()");
pw.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
@Override
protected void onPause() {
super.onPause();
if ( pw != null ) {
pw.close();
}
}
}
程序编译好并在我的Android设备上运行。但是,在我检查外部存储器中的“AndroidWriteTxtFile.txt”文件后,我发现“Here onResume()”语句确实出现在此文件上,而“Here onTouch()”语句没有。
当我在Android onTouch事件方法中时,有谁知道为什么我无法将数据写入文本文件?
感谢您的任何建议。