在我的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()
或其他方法正确更新缓存文件?
编辑:
您走在正确的轨道上。您需要将文件保持打开状态以供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。)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句