Java Reference
In-Depth Information
Listening for File System Changes
Mobile devices are prone to a lot of changes in their environment, and the file system is
no exception. Many Java ME devices support removable file systems through memory
card slots, such as microSD or miniSD. Consequently, your application needs to be able
to detect when the user inserts or removes a card, and you need a way to enumerate the
mounted file systems. You can do this by registering a listener to the file system while
your application is running; the FCOP provides the
javax.microedition.io.file.
FileSystemRegistry
class to do this.
You register a listener using the
FileSystemRegistry.addFileSystemListener
method, passing an instance of a class implementing
javax.microedition.io.file.
FileSystemListener
. You override the
rootChanged
method as shown in Listing 7-2.
Listing 7-2.
Overriding the rootChanged Method
FileSystemListener l;
private void startListener() {
l = new FileSystemListener() {
public void rootChanged( int state, String rootName ) {
// Process the change here.
}
}
try {
FileSystemRegistry.addFileSystemListener( l );
}
catch(Exception ex) { /* Handle exception */ }
}
private void stopListener() {
if ( l != null ) {
try {
FileSystemRegistry.removeFileSystemListener( l );
}
catch(Exception ex) { /* Handle exception */ }
}
}
Any time you add or remove a file system, the system invokes your
rootChanged
method with two arguments. The first argument indicates the addition of a file system
root if you receive the
FileSystemListener.ROOT_ADDED
value, or the removal of a file sys-
tem if you receive the
FileSystemListener.ROOT_REMOVED
value. The second argument
indicates the name of the root used to access the file system that was added or removed.