You can use change listeners to receive notifications whenever a specified
file or folder has changes to its contents or metadata. A change listener
implements the
OnChangeListener
interface for the ChangeEvent
and receives a direct callback from the Drive service to a currently
connected client application.
You can add a change listener by calling the
DriveResourceClient.addChangeListener
method, passing in the file or folder you want to receive notifications for.
Listeners are only active for the duration of the current connection or until
you call the
DriveResourceClient.removeChangeListener
method.
The following example code demonstrates how to add a change listener for a file:
To remove a change listener from a file, you must call the
DriveResourceClient.removeChangeListener
method, passing in the
ListenerToken object
returned by DriveResourceClient.addChangeListener
.
The following code sample demonstrates how to remove a change listener applied to a Drive resource:
In addition to adding the listener to the file or folder you wish to receive
events for, your application must also implement the callback (changeListener
in this example) you passed in the addChangeListener
method call. The following
demonstrates a callback that prints the received events to a log.
For callbacks that take action, such as retrieving the latest version, you can use the
hasContentChanged
and
hasMetadataChanged
methods to determine whether the file contents, metadata, or both have changed.
Change subscriptions
Change subscriptions allow your application to receive ChangeEvent
notices
even when it is not running. For example, your application can show a
notification when a file or folder it cares about has changed, even if the
change occurs after the user has closed your app.
You can add a change subscription by calling the
DriveResourceClient.addChangeSubscription
method, passing in a reference to
the file or folder you want to receive notifications for. The subscription
remains until the next device reboot and stays active until the
DriveResourceClient.removeChangeSubscription
method is called for the same resource.
Add a change subscription
The following example code shows the logic you might implement to add a change subscription to a file:
Conversely, to remove a change subscription from a file, you can use code similar to the following example:
Handle change subscriptions events
To handle change subscription events you must create a class that extends
DriveEventService
and overrides the onChange
method. This is where
application-specific processing of the ChangeEvent
would occur.
The service must be defined in your application's manifest. In AndroidManifest.xml, create an entry for your service as a child of the application element.
Your application receives a ChangeEvent
whenever a file or folder gets
updated by another application on the device or the Drive API downloads changes
from the server.