【问题标题】:How to refresh a file reading every 5 minutes in Android?如何在Android中每5分钟刷新一次文件读取?
【发布时间】:2013-04-09 18:10:25
【问题描述】:

我试图每 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 分钟读取一次文件。

我将非常感谢任何帮助!

【问题讨论】:

    标签: android file android-activity refresh inputstream


    【解决方案1】:

    为什么要每五分钟检查一次?你可以使用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 上查看另一个很好的示例。

    附言在您的情况下,您可能会使用 ...

    new FileObserver(tarjeta.getAbsolutePath()+"/.Info/Prices/")
    
    file.equals("values.txt")
    

    ...可能还有更多的事件类型。

    只是一个想法......干杯!

    【讨论】:

      【解决方案2】:

      试试这样的:

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

      它的作用是将此 Runnable 推送到 ui 线程中,该线程会在 5 分钟(300000 毫秒)内将自身发布到同一线程中。

      【讨论】:

        猜你喜欢
        • 2013-11-17
        • 2016-11-10
        • 2017-06-11
        • 2020-07-09
        • 1970-01-01
        • 1970-01-01
        • 2021-09-07
        • 2020-06-23
        • 2022-12-18
        相关资源
        最近更新 更多