Skip to content
svenmeier edited this page Apr 23, 2012 · 35 revisions

Propoid-util offers convenience working with services and content.

Listening to services

With ServiceListenerBinder a service can easily allow activities or other services listen for changes. Create a subclass and return it from the onBind(Intent) method of your service implementation:

    public class FooService extends Service {
      private FooBinder binder = new FooBinder();

      public IBinder onBind(Intent intent) {
        return binder;
      }
     
      private void barChanged() {
        for (FooListener listener : binder.listeners()) {
          listener.onBar();
        }
      }
     
      private class FooBinder extends ServiceListenerBinder<FooListener> {
        public void onRegistered(FooListener listener) {
          listener.onBar();
        }
      }
    }

Your binder is handed each new listener to notify it of the current state.

To listen to this service you just have to create a subclass of ServiceListener:

    FooListener listener = new FooListener() {
      public void onBar() {
      } 
    };
    listener.register(context, FooService.class);

Don't forget to deregister when your context is destroyed:

    listener.deregister()

Preferences

Preference allows convenient typed access to a preference:

    Preference<Boolean> myBoolean = Preference.getBoolean(context, R.string.my_boolean);
    Preference<Integer> myInteger = Preference.getInteger(context, R.string.my_integer);

Thanks to the keys being declares in your strings.xml we have a build-time safe identification of preferences:

   <string name="my_boolean">my_boolean</string>
   <string name="my_integer">my_integer</string>

Most of the time (but not necessarily) you want the user to be able to change the preference:

    <CheckBoxPreference
        android:key="@string/my_boolean"
        android:title="@string/my_boolean_title"
        android:summary="@string/my_boolean_summary"
        android:defaultValue="true"
    />
    <EditTextPreference
        android:key="@string/my_integer"
        android:title="@string/my_integer_title"
        android:summary="@string/my_integer_summary"
        android:numeric="integer"
        android:defaultValue="10"
    />

Note that in the latter case - an EditTextPreference with numeric input - any entered String will automatically be converted to the requested type when accessed via Preference.

Clone this wiki locally