如何比较android中的两个数字?

时间:2017-04-29 00:06:57

标签: android

当您打开我的应用时,我的代码会获取文件夹的大小并将大小存储在long A中。在您第二次打开它时,它会执行相同操作,但将其存储在long B中。在此之后,应该将旧大小与新大小进行比较,通过这样做,我能够确定文件是否已被修改或调整过。

private long A;
private long B;
private boolean AorB = true;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    File file = new File(Environment.getExternalStorageDirectory().getPath() + "/X ADB/");
    long size = getFolderSize(file);
    Toast.makeText(getApplicationContext(), String.valueOf(size), Toast.LENGTH_LONG).show();

    // store size in A and then B and then A and so on
    if (AorB == true) {
        // assign value to A
        A = getFolderSize(file);
        AorB = false;
    } else {
        // assign value to B
        B = getFolderSize(file);
        AorB = true;
    }
    // compare old size with new size
    if (A == B) {
        Toast.makeText(getApplicationContext(), "equal", Toast.LENGTH_LONG).show();
    } else {
        Toast.makeText(getApplicationContext(), "unequal", Toast.LENGTH_LONG).show();
    }
}

// get directory size
public static long getFolderSize(File dir) {
    long size = 0;
    for (File file : dir.listFiles()) {
        if (file.isFile()) {
            size += file.length();
        } else
            size += getFolderSize(file);
    }
    return size;
}

}

真正的问题是,我的吐司总是说不平等,每次打开我的应用程序时,我甚至都没有更改或修改会影响大小的任何文件。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

关闭应用时,请使用SharedPreference保留该值。

// Don't forget to define the variable. 
// You may use whatever name you like.
private static final String MY_PREFS_NAME = "my_shared_pref";

保存数据

SharedPreferences.Editor editor 
       = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putLong("size", size);
editor.commit();

加载数据

SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE); 
long loadedSize = prefs.getLong("size", 0);