How can I tell if a file is currently being written to?
I'm saving a fairly large bitmap in a background thread. It takes about a second. The main thread will try to load the same file into a canvas. How can I tell the main thread to wait until it has finished saving?
Edit:
I wanted to know how to check on the file, not how to wait; sorry for the misunderstanding.
The bitmap object was removed from the main thread's memory for various reasons.
Is there a standard way to do check if the file is being used, or should I just use a work开发者_JS百科around?
The FileObserver
class suits your needs perfectly. Here is the documentation. It's easy to use. When a observed file is closed after writing, the onEvent
callback is called with CLOSE_WRITE
as the parameter.
Use AsyncTask
to run a background thread and update UI when finished. It was designed for specifically this task.
Also note that you should never hog the UI thread (like waiting for background thread to finish) because this blocks UI interaction and your UI will be unresponsive or worse you might get an ANR.
Android's AsyncTask will be suitable for this problem: http://developer.android.com/reference/android/os/AsyncTask.html
You can update the bitmap in doInBackground, and then onPostExecute you can notify the main thread do draw it to canvas.
edit/what he said
精彩评论