Previous Topic

Next Topic

Book Contents

Book Index

Preferences Service

This document is illustrating the usage model of the Preferences Service.

Overview

The figure below is of a Preferences tree, created by the simple bundle from the code example, that uses both interfaces, PreferencesService and Preferences. The root represents a node with the system preferences. There are two more nodes and each of them represents the preferences for a specified user. (For the example the users correspond to user1 and user2). The put(String, String) method associates the specified value with the specified key in this preference node. The string "FirstUser" is the specified value for the user1. The get(String, String) method returns the value associated with the specified key in this preference node.

By using getUsers() method, all the users could be seen, as this method returns their names as strings.

Preferences tree:

Registering Bundle

This service is registered by OSGi Preferences Bundle.

Preferences example:

  package test.prefs;

  import org.osgi.service.prefs.PreferencesService;
  import org.osgi.service.prefs.Preferences;
  import java.io.IOException;
  import org.osgi.framework.*;

  public class PrefsTestActivator implements BundleActivator {
    ServiceReference prefsRef;
    private static PreferencesService ps;
    
    public void start(BundleContext bc) throws BundleException {
      prefsRef = bc.getServiceReference("org.osgi.service.prefs.PreferencesService");
      PreferencesService ps = (PreferencesService) bc.getService(prefsRef);
      // creating the preferences tree
      Preferences system = ps.getSystemPreferences();
      Preferences user1 = ps.getUserPreferences("User1");
      Preferences user2 = ps.getUserPreferences("User2");
      //specify a value and associate it with a key
      user1.put("name", "FirstUser");
      // returns the value associated with the specified key
      user1.get("name", "user1");
      String [] allUsers = ps.getUsers();
      System.out.println(allUsers);
    }

    public void stop(BundleContext bc) {
      bc.ungetService(prefsRef);
    }
  }