An application can
add a FolderListener to folders of
type INBOX so that the application is notified when new messages arrive in the user’s
inbox. If an application does not receive notification when new messages arrive, it is
likely because the FolderListener was not added to all the appropriate folders.
For most corporate
users, the inbox folder is stored at the root level of the folder hierarchy.
The simulator uses this corporate inbox as well. For some users, however, an
inbox can exist at one or more levels lower in the hierarchy. This is often
true for users with a BlackBerry Web Client account.
Consider the following code:
try {
Store s = Session.waitForDefaultSession().getStore();
Folder[] folders = s.list(Folder.INBOX);
Folder inbox = folders[0];
inbox.addFolderListener(this);
}
catch (Exception e) {}
}
The Store.list() method only returns folders at the root level of the folder hierarchy.
If the user’s inbox is in a subfolder, it is not returned, so the listener is not
added.
The following sections describe two possible solutions to this issue.
(1) Add a FolderListener to the Store
Instead of adding a FolderListener to a specific INBOX-type folder, you
can add a FolderListener to the entire Store. Then, in the
implementation of the FolderListener methods, evaluate whether the
FolderEvent is for a received (inbound) message.
The following code demonstrates how to do this:
Store store = Session.waitForDefaultSession().getStore();
store.addFolderListener(new FolderListener() {
public void messagesAdded(FolderEvent e) {
if( e.getMessage().isInbound() == true )
{
//message is a new received message
//perform some task here
}
}
//implement other FolderListener methods
//…
});
(2) Search recursively for INBOX folders
An alternative
approach is to iterate through the folder hierarchy and perform a recursive search to retrieve a
reference to all INBOX folders:
- Invoke
Store.list() with no type parameter to return a list of all
folders.
- List all folders at the top level of type
.
- Iterate through each of the other folders, and repeat these steps
until you have searched all the available subfolders.
The following sample code demonstrates how to search for INBOX folders and add a
FolderListener to each one.
public class folderListenerImpl implements FolderListener {
…
}
...
Store store = Session.waitForDefaultSession().getStore();
Folder[] folders = store.list();
for (int i = 0; i < folders.length; ++i) {
Folder f = folders[i];
recurse(f);
}
public void recurse(Folder f)
{
if ( f.getType() == Folder.INBOX )
{
f.addFolderListener(folderListenerImpl);
}
Folder[] farray = f.list();
for (int i = 0; i < farray.length; ++i)
{
recurse(farray[i]);
}
}