问题
I'm totally new to Java and Android, so I think I'm probably missing something obvious. I'm writing an app where I sample the orientation sensor and write the result to a file on the SDCard as well as display it in a log on the screen. Everything works fine while the screen is on. Since I want to also operate while the screen goes dark, I added code to acquire a PARTIAL_WAKE_LOCK. From what I can tell, when the screen goes dark the sensors are still being sampled (making me think the wake lock worked), but none of the results are written to the SDCard. I think this is what is happening, because when I reawaken the screen by pressing the menu key, the log on the screen has all the transitions displayed that took place while the screen was off. But, when I look at the file created on the SD card, the only transitions recorded in the file are the ones that occurred while the screen was on. As for how I'm writing the file I have tried (I think I'm saying this right...) a FileWriter wrapped in BufferedWriter, and a FileWriter wrapped in a FileOutputStream. At first, the orientation sensor wasn't working even though I had the wake lock until I learned a work around where I added a BroadcastReceiver for Intent.ACTION_SCREEN_OFF and when I get it, I unregister the orientation listener, then re-register it. Do I need to "unregister" the FileWriter and "re-register" it or something? The weird part is that the output file contains all orientation changes before the Intent.ACTION_SCREEN_OFF is received, and all of them after Intent.ACTION_SCREEN_ON is received when I power the screen back up, but nothing in between.
I'm writing for Android 1.6 (I have a G1) My project is set to use SDK 4
回答1:
Are you checking if external storage is available as described here? It may be simply unwritable at that time. There's also code in the docs for a external storage BroadcastReceiver. You could use that to wait until storage is available before writing.
来源:https://stackoverflow.com/questions/4742829/not-able-to-write-to-sdcard-while-screen-is-off-even-though-i-have-partial-wake