19
19
import java .util .HashMap ;
20
20
import java .util .Map ;
21
21
import java .util .Properties ;
22
+ import java .util .Timer ;
23
+ import java .util .TimerTask ;
22
24
23
25
/* Stores reports in memory (mCurrentReports) until MAX_REPORTS_IN_MEMORY,
24
26
* then writes them to disk as a .gz file. The name of the file has
25
27
* the time written, the # of reports, and the # of cells and wifis.
26
28
*
27
- * Each .gz file is typically 1-5KB.
29
+ * Each .gz file is typically 1-5KB. File name example: reports-t1406863343313-r4-w25-c7.gz
28
30
*
29
31
* The sync stats are written as a key-value pair file (not zipped).
30
32
*
@@ -51,6 +53,7 @@ public class DataStorageManager {
51
53
private ReportBatchIterator mReportBatchIterator ;
52
54
private StorageIsEmptyTracker mTracker ;
53
55
private ReportFileList mFileList ;
56
+ private Timer mFlushMemoryBuffersToDiskTimer ;
54
57
55
58
final static String SEP_REPORT_COUNT = "-r" ;
56
59
final static String SEP_WIFI_COUNT = "-w" ;
@@ -417,13 +420,33 @@ public synchronized void saveCurrentReportsToDisk() throws IOException {
417
420
public synchronized void insert (String report , int wifiCount , int cellCount ) throws IOException {
418
421
notifyStorageIsEmpty (false );
419
422
423
+ if (mFlushMemoryBuffersToDiskTimer != null ) {
424
+ mFlushMemoryBuffersToDiskTimer .cancel ();
425
+ mFlushMemoryBuffersToDiskTimer = null ;
426
+ }
427
+
420
428
mCurrentReports .reports .add (report );
421
429
mCurrentReports .wifiCount = wifiCount ;
422
430
mCurrentReports .cellCount = cellCount ;
423
431
424
432
if (mCurrentReports .reports .size () >= MAX_REPORTS_IN_MEMORY ) {
425
433
// save to disk
426
434
saveCurrentReportsToDisk ();
435
+ } else {
436
+ // Schedule a timer to flush to disk after a few mins.
437
+ // If collection stops and wifi not available for uploading, the memory buffer is flushed to disk.
438
+ final int kMillis = 1000 * 60 * 3 ;
439
+ mFlushMemoryBuffersToDiskTimer = new Timer ();
440
+ mFlushMemoryBuffersToDiskTimer .schedule (new TimerTask () {
441
+ @ Override
442
+ public void run () {
443
+ try {
444
+ saveCurrentReportsToDisk ();
445
+ } catch (IOException ex ) {
446
+ Log .e (LOG_TAG , "mFlushMemoryBuffersToDiskTimer exception" , ex );
447
+ }
448
+ }
449
+ }, kMillis );
427
450
}
428
451
}
429
452
0 commit comments