如何在Android中每5分钟刷新一次文件?
问题描述:
我试图每5分钟阅读一个文件,但我真的不知道如何!如何在Android中每5分钟刷新一次文件?
这是我的代码:
public class MainActivity extends Activity implements OnClickListener {
Button bVe, bCl, bCo, bAd;
File tarjeta = Environment.getExternalStorageDirectory();
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bVe = (Button) findViewById(R.id.bVehiculos);
bCl = (Button) findViewById(R.id.bClientes);
bAd = (Button) findViewById(R.id.bAdmin);
bVe.setOnClickListener(this);
bCl.setOnClickListener(this);
bAd.setOnClickListener(this);
File file1 = new File(tarjeta.getAbsolutePath()+"/.Info/Prices", "values.txt");
try {
FileInputStream fIn1 = new FileInputStream(file1);
InputStreamReader archivo1 = new InputStreamReader(fIn1);
BufferedReader br1 = new BufferedReader(archivo1);
String linea1 = br1.readLine();
String texto1 = "";
while (linea1!=null)
{
texto1 = texto1 + linea1 + "\n";
linea1 = br1.readLine();
}
br1.close();
archivo1.close();
} catch (IOException e) {
Toast.makeText(this, "Cant read", Toast.LENGTH_SHORT).show();
}
我需要的,而我在这个活动中,它会读取文件每5分钟。
我会很感激任何帮助!
答
尝试类似的东西:
getHandler().post(new Runnable() {
@Override
void run() {
(code to read file)
getHandler().postDelayed(this,300000);
}
});
它的作用是推动这个Runnable接口到用户界面线程,职位本身为5分钟(300000毫秒)相同的线程。
答
为什么你想每五分钟检查一次?你可以使用一个FileObserver
:
FileObserver observer =
new FileObserver(Environment.getExternalStorageState() +"/documents/") {
@Override
public void onEvent(int event, String file) {
if(event == FileObserver.MODIFY && file.equals("fileName")){
Log.d("TAG", "File changed");
// do something
}
}
};
是不是更容易和更少的CPU /电池消耗,是吗?在https://gist.github.com/shirou/659180看到另一个很好的例子。
p.s.在你的情况下,你可能会使用...
new FileObserver(tarjeta.getAbsolutePath()+"/.Info/Prices/")
file.equals("values.txt")
...和可能更多的事件类型。
只是一个想法...干杯!