在我的Dropbox文件系统中,有一个文件' check.txt'包含值(0/1),我必须每5分钟检查一次
对Dropbox的访问是成功的,但读取此文件并不总是正确的
首先,文件包含0,第一个读数返回正确的值(0)。然后,如果我手动将1中的值更改为文件,则下一次读数将再次返回值0,并在多次读数后返回正确的值。
我使用Dropbox Synch,我的Android版本是4.3
这是代码的一部分:
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
try {
DbxAccountManager AcctMgr = DbxAccountManager.getInstance(getApplicationContext(), DropboxActivity.appKey, DropboxActivity.appSecret);
DbxFileSystem dbxFs = DbxFileSystem.forAccount(AcctMgr.getLinkedAccount());
DbxFile file = dbxFs.open(DropboxActivity.path);
DbxFileStatus status = file.getSyncStatus();
if (!status.isCached) {
file.addListener(new DbxFile.Listener() {
@Override
public void onFileChange(DbxFile file) {
try {
if (file.getSyncStatus().isCached) {
file.update();
// deal with the new value
Log.e("TAG", "*** VALUE *** " + file.readString());
}
} catch (DbxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
if((file.readString()).equals("0")) {
Log.d("TAG", "Value: " + file.readString());
}
else {
Log.d("TAG", "Value: " + file.readString());
flag = 1;
stopAlarm();
startService(new Intent(this, GpsService.class));
}
file.close();
} catch(Exception e) {
e.printStackTrace();
}
stopSelf();
return startId;
}
我如何使用file.getNewerStatus()
和file.update()
或其他方法正确更新缓存文件?
编辑:
答案 0 :(得分:1)
你走在正确的轨道上。您需要保持文件打开以便Sync API下载新内容,然后您需要监听更改,因此请务必不要关闭它。见https://www.dropbox.com/developers/sync/start/android#listeners。像这样:
DbxFileStatus status = testFile.getSyncStatus();
if (!status.isCached) {
testFile.addListener(new DbxFile.Listener() {
@Override
public void onFileChange(DbxFile file) {
if (file.getSyncStatus().isCached) {
file.update();
// deal with the new value
}
}
});
}
执行此操作后,无需每五秒检查一次文件...每次更改时都会收到通知。
(另外,您可能希望查看Datastore API。)