2013-04-09 101 views
1

我試圖每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分鐘。

我會很感激任何幫助!

回答

0

嘗試類似的東西:

getHandler().post(new Runnable() { 
    @Override 
    void run() { 
     (code to read file) 
     getHandler().postDelayed(this,300000); 
    } 
}); 

它的作用是推動這個Runnable接口到用戶界面線程,職位本身爲5分鐘(300000毫秒)相同的線程。

2

爲什麼你想每五分鐘檢查一次?你可以使用一個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") 

...和可能更多的事件類型。

只是一個想法...乾杯!

相關問題