Geachte heer Bosman. Een open brief aan cultuurtheoloog Frank G. Bosman

Geachte heer Bosman,

zoals bijna elke dag luister ik op de terugweg van mijn werk naar het programma “Dit is de dag”. U bent daar zo nu en dan te gast om een stelling voor te leggen waar dan even over wordt gediscussieerd.

Voordat ik met mijn betoog begin zal ik mij eerst even voorstellen. Mijn naam is Jeroen Somhorst. Van beroep ben ik Software Developer bij een bedrijf in Den Bosch en kom ik bij diverse bedrijven in het land over de vloer. En dit allemaal met een handicap die zorgt dat ik rolstoelgebonden ben. Over het algemeen ben ik het eens met uw stellingen echter vandaag schoot uw stelling mij in het verkeerde keelgat.

Uw stelling is als volgt:
‘Knuffel gehandicapte niet dood met aparte wetten’

Wat u daarmee bedoelt is, zoals ik het interpreteer, dat het ratificeren van het VN verdrag voor de rechten van de gehandicapte mens ook averechts kan werken. Er zit een kern van waarheid in. Dat als er te strikte wetten worden opgezet deze de zelfredzaamheid van de ‘gehandicapte medemens’ kunnen belemmeren. Om uw standpunt kracht bij te zetten neemt u als voorbeeld uw vader. Uw vader heeft op jonge leeftijd een been amputatie moeten ondergaan waardoor hij de rest van zijn leven veel dingen ‘anders’ moest doen dan anderen. Zijn vader, uw opa, heeft hem daar altijd op gewezen. Een harde opvoeding werd geconcludeerd.

Nu neemt u dit voorbeeld en gebruikt dit om een beeld te schetsen alsof gehandicapten door dit verdrag verwent zouden raken. Ik kan u vertellen dat dit niets met dit verdrag te maken hoeft te hebben. Dit heeft in de eerste plaats te maken met de opvoeding van de ouders. Als ouders alleen maar zicht hebben voor de problemen van het kind en het wijs maken dat het vooral anders is dan kweek je in feite ‘verwendicapten’, zoals dat in het jargon genoemd wordt. Oftewel gehandicapten die het handje ophouden en niets zelf doen.

Een andere factor die bepalend is, is het onderwijs. Toen ik nog op het voortgezet onderwijs zat (zo’n 18 jaar terug ) was er geen toekomstperspectief vanuit de school. Er werd niet altijd alles uitgehaald wat er in zat want je had een handicap. Althans dat is wat mij bij gebleven is. Gelukkig door mijn opvoeding is mij geleerd dat gehandicapt zijn vooral mijn eigen probleem is en dat ik er zelf alles van moet maken. Dat is niet een harde opvoeding dat is een opvoeding zoals het zou moeten. Immers, iedereen dient iets van zijn eigen leven te maken. Of je nu doof, blind, mank of bruin bent. Dit brengt mij op het volgende.

Dit kabinet is een aantal jaren geleden de weg ingeslagen van de zgn. participatie maatschappij. Daarmee wordt bedoeld dat men het liefste wil dat mensen met een ‘arbeidsbeperking’, deel moeten nemen aan de maatschappij. Dat begint echter niet bij het arbeidsproces maar veel eerder. Dat begint bij het naar de kinderdagopvang gaan, het naar school gaan en daar gewoon mee kunnen doen met de rest.

Daar hoort bij dat men in de pubertijd net als andere scholieren eens lekker kan gaan stappen. Daar hoort bij dat men wat dieper in het glaasje kan kijken en in een rolstoel tegen een lantaarnpaal in slaap valt.

De overheid heeft als taak als zij een participatie maatschappij wil dit ook te faciliteren en het niet simpelweg aan de maatschappij over te laten met de insteek van ‘zoek ‘t maar uit’. Als we kijken naar de afgelopen jaren dan zien we dat er steeds meer verbeterd maar dat het simpelweg niet snel genoeg gaat. Zo zijn de meeste buslijnen in Nederland voorzien van de nodige aanpassingen (oprijplaten, lage stop knoppen etc.) maar zijn de treinen in Nederland ( En nee, Nederland is niet alleen maar de randstad) nog steeds niet toegankelijk. De gehandicapte is nog steeds aangewezen op een systeem van het aanvragen van hulp en hopen dat men er maar uitgehaald wordt omdat men dit niet zelf kan. Een voorbeeld van mijzelf is een treinreis waarbij ik uitstaphulp had geregeld op station B maar ik kom, door een fout van de machinist, op station C terecht. Er waren gelukkig mensen die mij de trein uit hielpen maar het zou toch fijn zijn als ik zelf ook weer de trein in had gekund en niet een half uur had moet staan wachten zodat alle hulptroepen waren gemobiliseerd! Dit sluit niet aan bij de wens van een participatie samenleving.

Een ander punt is de toegankelijkheid van gebouwen zoals horeca. Als je wilt als overheid dat mensen met een handicap mee doen in de maatschappij dan betekend dat dat de lokale overheid hulp moet kunnen bieden aan ondernemers om de onderneming ook toegankelijk te maken. Vrienden willen je vast wel het café in tillen maar wat nu als je alleen maar vrienden in een rolstoel hebt? Moet ik mij dan maar aanpassen en in een café komen waar het alleen maar gaat over de poepluiers en hoe slecht de uitkeringen zijn in dit land? Is het echt nodig om twee groepen te creëren terwijl we allemaal één maatschappij zouden moeten zijn?

Zoals gezegd kan de lokale overheid genoeg doen om ondernemers bewust te maken van dit probleem. We hebben namelijk in de afgelopen 20~30 jaar gezien dat de maatschappij zelf er niet genoeg aan doet zelfs semi overheid niet.  Want zoals u zelf zei: “Onze sympathie ligt onmiddelijk bij de persoon die het stoepje niet op komt. Er moet iets aan trappen of wc’s gebeuren en willen we het meteen zelf regelen.” Nou meneer Bosman. Als dat ook daadwerkelijk gebeurde dan hadden we dit hele verdrag niet nodig gehad.

Als laatste punt wil ik nog even een vraag stellen. Waarom hebben we in Nederland eigenlijk speciale invalide toiletten? Waarom is dat niet simpelweg geïntegreerd in het heren of dames toilet zoals in andere landen om ons heen gemeengoed is?  Hoeven we er ook niet extra ruimte voor te creëren en hebben we toch aan onze plicht voldaan..

met vriendelijke groet,

Jeroen Somhorst

AngularJS : 1 Month later

Exactly one month go I posted a little message stating that I’m going to venture into the world of angularJS. This blogpost is for myself as a post-it note to keep the most important parts easy to find:

  1. the framework is awsome
  2. the framework is awsome
  3. the framework is awsome
  4. the framework is awsome

$scope

keeping track of scope variables can be a pain in the ###. Use $scope.$watch(‘<variable name>) to get notified about changes. first call is always some sort of initialization call!

use inline scopes in directives, this way the directive can be mean and clean.

scope: {

variable: "outervariable",

variable: "@attribute",

}

$http

use $http for low level ajax calls. $http uses promises. Promises are a observer/observable like tech to call funtions when a specified asynchronous task completes. When multiple ‘objects’ use the same service add a addListener method like so

var service = function($scope, $http) {
 var listeners = [];
 var self = this;
 this.addListeners = function(l) {
 this.listeners.push(l);
 }

 this.doGet = function() {
 $http.get('<someurldotstuff', self.onSuccess, self.onError);
 }

 this.onError = function(data) {
 for (var i = 0; i < listeners.length; i++) {
 listeners[i].onError(data);
 }
 }

 this.onSuccess = function(data) {
 for (var i = 0; i < listeners.length; i++) {
 listeners[i].onSuccess(data);
 }
 }
}

This way you can have multiple ‘listeners’ and don’t worry in your service on what is happening and break things by changing parsing the result.

Controllers

Don’t use anonymous functions!! Use a function defined at /App/controllers.js It makes your life easier

When defining a controller be aware of the DI properties. Always check the order of things 😉

Divide and conquer

Use the following app structure*

– /App

/App/libs : Contains all the javascript libraries needed to get it working such as moment.js or something similar

/App/pojo: Contains your ‘classes’ that are to be used. For instance in my runkeeper project I have a pojo for a workout, for a list of workouts and for heartrate data.

/App/app.js: Main module for the project.

/App/controller.js: Controller javascript. Contains all the controllers used throughout the application. no mather where they are used, in directives or just as a basic view controller.

/App/services.js: service object definitions module

/App/directives.js: main service definition module. Uses controller.js and service.js to get the work done. *be aware of this in <html><header>

/Templates: contains the main view templates

/Templates/partials: contains sub templates such as used by directives. 

* thinking about moving them into the /App directory

AngularJS a new world opens

In my spare time I’m currently looking into AngularJS. Before I started working on it I was skeptical. The main reason for it is that it’s  JavaScript framework and I’m not particularly fan of this language at all. Error handling is  mess and the fact that it’s weakly typed isn’t great either.

So why start using AngularJS? I think that the main reason can be described as ‘easy of use’. Because web apps are the way to go I have  to find a tool that can help me write those apps with the least effort. Together with the templating engine and the fact that there is already a lot of stuff in the framework I don’t need to write a whole bunch of code myself just to get a input field to change its value when someone presses a button. Another thing I like about angular is the structure.

Currently, working on my first real app, I have a main module ( the app ) which has dependencies with other modules. The main app is really straight forward and contains only the global things like a user object and so fort. The other modules are in fact directives that contain isolated business logic.

And next to that I have a service module. This module is only used for storing factory definitions. One for connecting to the login REST endpoint, another one for connecting to the data REST endpoint etc. etc. I’m planning on adding some blog posts regarding angular in the future. Don’t expect these to be tutorial like posts but they will be more like post it notes so I wont forget the things I already did in the past 😉

Android Development: Simple collision detection

For my App I need to know when a user drags a specified element on top of another element. For instance when they drag one of their attack cards to the deck of the oponnent. On top of that I also need to know if the current location will result in an attack movement or just in a drag in open space. In both situations the game should do something else. So how can we detect if the current location is resulting in an attack? Simple by using the Rect.intersects method like so

package eu.jeroensomhorst.myfirst.util;

import android.graphics.Rect;
import eu.jeroensomhorst.myfirst.game.ui.UICard;

public final class CardUtil {

	public static boolean touchedCard(UICard c1, UICard c2){
		if(!(c1 == null || c2 == null)){
			Rect rect1 = new Rect((int)c1.x,(int)c1.y,(int)c1.x+c1.getWidth(),(int) (c1.getHeight()+c1.y));
			Rect rect2 = new Rect((int)c2.x,(int)c2.y,(int)c2.x+c2.getWidth(),(int) (c2.getHeight()+c2.y));
			return intersect(rect1, rect2);	
		}
		return false;
	}
	
	public static boolean touchedCard(UICard c, float x, float y) {
		
		Rect cardLocation = new Rect((int) c.x, (int) c.y, (int) c.x
				+ c.getWidth(), (int) c.y + c.getHeight());
		Rect location = new Rect((int)x,(int)y,(int)x+200,(int)y+200);
		
		return intersect(location,cardLocation);
	}
	
	private static boolean intersect(Rect r1,Rect r2){
		return r1.intersect(r2);
	}
}

this class implements a few utility methods. They bassicaly to the same thing. They convert the given parameters into two Rect instances and call the intersect method of the first Rect.  With this little tip you can easily integrate some basic collision detection. with this knowledge we can easily find out if the current user is attacking the enemy and which card is being attacked with the following code:

for(UICard c: this.enemyFrontLine){
					if(CardUtil.touchedCard(currentlyTouchedCard, c)){
						enemyFrontLineCard  = c;
						break;
					}
						
				}

In this example we loop over the enemyfrontline cards and for every card we check if it intersects. If that is the case we break out of the loop and use the found card to do the stuff we want to do with it ( in my case find out which card has ‘won’ and respond accordingly.

 

Android Development: Loading image

In a previous post I talked about loading bitmaps. In this post I will tell something about caching the loaded resources. For this I created a little util class. To give you an example how to use it here is the code. I will explain it step by step.

private Matrix scaleMatrix;

public UICard build(Card c, int color) {

	if (getBitmap(c, color) == null) {
		this.loadBitmap(c, color);
	}

	if (getBitmap(Card.Front, color) == null) {
		this.loadBitmap(Card.Front, color);
	}
	
	
	UICard card = new UICard(c, color);
	card.setBackImage(getBitmap(c, color));
	card.setFrontImage(getBitmap(Card.Front, color));
	return card;
}

private Bitmap getBitmap(Card c, int color) {
	LruCache<Card, Bitmap> cache = this.imageCacheRed;
	if (color == UICard.BLUE) {
		cache = this.imageCacheBlue;
	}
	return cache.get(c);
}

private void loadBitmap(Card c, int color) {
	int drawable = getRedDrawable(c);
	if (color == UICard.BLUE) {
		drawable = getBlueDrawable(c);
	}
	Bitmap cardImage = BitmapFactory.decodeResource(context.gtResources(),drawable);

	cardImage = Bitmap.createBitmap(cardImage, 0, 0, cardImage.getWidth(),cardImage.getHeight(), scaleMatrix, true);

	if (color == UICard.RED) {
		this.imageCacheRed.put(c, cardImage);
	} else {
		this.imageCacheBlue.put(c, cardImage);
	}
}	

private void init() {

	final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
	final int cacheSize = maxMemory / 4;
	this.imageCacheBlue = new LruCache<Card, Bitmap>(cacheSize) {
	@Override
	protected int sizeOf(Card key, Bitmap bitmap) {
		return (bitmap.getRowBytes() * bitmap.getHeight()) / 1024; 
		}
	};

	this.imageCacheRed = new LruCache<Card, Bitmap>(cacheSize) {

	@Override
	protected int sizeOf(Card key, Bitmap bitmap) {
		return (bitmap.getRowBytes() * bitmap.getHeight()) / 1024	}
	};

	Matrix m = new Matrix();
	m.preScale(0.1f, 0.1f);
	this.scaleMatrix = m;
}
}

When the View needs an image it calls the method ‘build’ (3).

It passes a Card object that specifies which card we want to load. We also need to tell the builder which color we need  ( two sides in this game remember? )

It will first check if bitmap belonging to the card specified already has been loaded in the past (20-26).  It therefore will get the correct cache (21-24) ( Yes I have 2 cache’s one for each side ). When the card has not been found in the cache it should be loaded (  5 and 6). Therefore we find the correct drawable (from the R object ) (29-32) and create a bitmap out of it (33-35). We scale it down using a scale matrix and we put the image back in the correct cache (37-41). After that we try to load it again (line 15-16).

By using this approach we asure the app that it will always be using the same instance of a particular bitmap.

I hope this will help you a bit developing your own game apps.

Android Development: Adding touch support

When creating an App users need to somehow interact with your program. Mostly this will include touch support. To set up touch support you need to do the following Warning lots of code !! I will try to explain everything step by step.

Lines 8, 39,73: Listen to the various events.

Line 11-28: When a mouse-down event is detected it means that we are in a new cycle of down->move->up events. In this case it means that we first have find out if the current location was not the previous location and if this is not the case we need to find out if we touched something we are interested in ( 13 ). If so we will do all kinds of stuff with that element and call invalidate. This causes the UI to redraw everything.

Line 39 – 65: If the action_up is detected it means that we are done with our current operation. In this case it means that we have to find out where currently are situated. If that location somehow intersects with another element we are interested in it will cause a change in the ui ( in this case some cards will be redrawn with another image )

73 – 83: Touch support means in most cases drag support. We do this simply by getting our current location and move the current selected element ( a card ) to that new position. Since the x and y coordinates of the event are left/top coordinates we need to change that location so that we don’t touch the top/left corner of that element but somewhat in the middle this feels a bit more natural to the user.

// Add a TouchListener
	@Override
	public boolean onTouchEvent(MotionEvent event) {

		Log.d(TAG, "Event : " + event.getAction());

		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			Log.d(TAG, "X: " + event.getX());
			Log.d(TAG, "Y: " + event.getY());
			if (event.getX() != this.previousX
					&& event.getY() != this.previousY) { // we changed
				if (this.touchedMyDeck(event.getX(), event.getY())) {
					if((myDrawnCard!=null && myDrawnCard.getParent().equals(Card.Empty))|| myDrawnCard == null){
						if(myDrawnCard!=null){
							myDrawnCard.recycle();
						}
						if (StrategoGame.getInstance().showCurrentCardOnStack() != null) {
							Card c = StrategoGame.getInstance()
									.drawCardFromStack();
							this.myDrawnCard = new UICard(c,
									StrategoGame.getInstance().getColor(), getContext(),
									this.drawnCardX, this.drawnCardY);
							myDrawnCard.flip();
							this.invalidate();
						}
					}

				} else

				if (this.touchedDrawnCard(event.getX(), event.getY())) {
					currentlyTouchedCard = this.myDrawnCard;

				}

			}

			break;
		case MotionEvent.ACTION_UP:
			if (currentlyTouchedCard != null) {
				UICard frontlineCard = null;

				for (UICard c : this.frontLine) {
					if (CardUtil.touchedCard(currentlyTouchedCard, c)) {
						frontlineCard = c;
						break;
					}
				}

				if (frontlineCard != null) {
					if (frontlineCard instanceof UICardPlaceHolder) {

						int index = frontLine.indexOf(frontlineCard);
						
						UICard newUICard = (UICard) currentlyTouchedCard.clone(getContext());
						if(currentlyTouchedCard.isFlipped()){
							newUICard.flip();
						}
						
						frontLine.set(index, newUICard);
						this.currentlyTouchedCard = null;
						this.myDrawnCard = null;
					}

				}
			}
			// TODO Find out if currentlyDrawnCard is touching frontline. If so
			// check if frontline is empty location
			// IF so add this card to that spot in the frontline else move card
			// to default location.

			break;
		case MotionEvent.ACTION_MOVE:
			if (this.currentlyTouchedCard != null) {

				this.currentlyTouchedCard.x = (int) event.getX()
						- (currentlyTouchedCard.getWidth() / 2);
				this.currentlyTouchedCard.y = (int) event.getY()
						- (currentlyTouchedCard.getHeight() / 2);

			}

			break;
		}
		return true;
	}

This concludes this little blogpost about touch…

Android development: Loading bitmaps

If you want to add graphics to your application you can use the following information

Create a custom Activity like this

public class GameActivity extends Activity implements Observer{

	private static final String TAG = "StrategoGameActivity";
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setContentView(new StrategoGameView(this));
		ActionBar actionBar = getActionBar();
		actionBar.hide();
        
	}
    
	
	@Override
	public void update(Observable observable, Object data) {
		// TODO Auto-generated method stub
		
	}

}

Create your own View ( in this example StrategoGameView)

public class StrategoGameView extends View{

public StrategoGameView(Context context){
 super(context);
 initView(context);
}

private InitializeView(Context c){
...
}

}

I personally find it a good practice to call an initialize method in your constructor. This way you can decide if you want to make it public so when needed you can reinitialize easily.

Now if you want to add a Bitmap to your application you need to do the following things

Add a res/drawable directory to your project

create some fancy images and save them in this directory.

After a rebuild you can get a pointer to the using the R.drawable object like this

Bitmap mybitmap = BitmapFactory.decodeResource(context.getResources(),R.drawable.cardtop_blue);

to draw the bitmap to the screen you need to add a onDraw method to your View like this:

protected void onDraw(Canvas canvas){

canvas.drawBitmap(mybitmap,x,y, null);


}

 

Android Development: Responding to a socket request

Warning: Worst Blog post written ever in history!

in my current project, a simple multiplayer game, I need to react on a connection request from another device. Currently both devices start their own service discovery. On one device I go to the list of found services and pick on. On the click the ServiceHelper will try to resolve the chosen device and if successful it will start communication sending a simple ‘gameplayrequest’ string.

the other device reacts to this with a OK response. This response is generated only when the user accepts the ‘invitation’. Ok and now some code 😉

try {
	this.server = new Socket();
	server.connect(new InetSocketAddress(location,this.port));
	this.sendRequest(new GameRequestResponseNotifier(GameRequestResponseNotifier.REQUEST_CONNECTION,null));
			
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

....

public void sendRequest(Notifier n) {
 ClientRequestThread ct = new ClientRequestThread(n,this);
 Thread t  = new Thread(ct);
 t.start();
}

..
public void run() {
  try {
    Socket server = instance.getServerConnection();
    PrintWriter writer = new PrintWriter(instance.server.getOutputStream(),true);
				
   writer.println(notifier.toString());
if(!(notifier instanceof OKNotifier)){
	BufferedReader reader = new BufferedReader(new InputStreamReader(server.getInputStream()));
	String data = reader.readLine();
	instance.notifyAll(data);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

These are some code snippets First we need to connect to the other device after we done that we need to send a response. This has to be done in a separate thread. The reason for this is that Android does not allow any heavy operations in the main thread. When we have notified the device that we are ok with the request the result is notified to all our listeners ( the view in this case )

And now the code to start resolving the chosen service

listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Object item = listView.getItemAtPosition((int) id);
				
				ServiceHelper.getInstance(null).addObserver((Observer) ListActivity.this);
				ServiceHelper.getInstance(null).resolveService(
						(NsdServiceInfo) item);
				Log.d(TAG, item.toString());
			}

		});

We get an instance of our service helper and subscribe ourselves to it

We start to resolve the service and logging which thing we clicked.

Now the update code in this activity

		if (data instanceof Notifier) {
			Notifier n = (Notifier) data;
			switch (n.toString()) {
			case Notifier.SERVICE_RESOLVE_SUCCESS:
				sendGameRequest();
				break;
			case Notifier.SERVICE_RESOLVE_FAILED:
				showUnabletoConnectToast();
				break;
			case GameRequestResponseNotifier.RESPONCE_CONNECTION_ALLOWED:
				Log.i(TAG,"Lets go to the next screen!");
			}
		}
	}

the update call first checks if the data that we receive is of the type notifier ( a class created by me to send data and some payload ). after we have resolved succesfully (see previous code snippet) we send a request to the server (first snippet) . The server will respond with an ok response ( or response_connection_allowed in this case ). We will log that for now but in the future this will cause a switch to another activity.

That’s it for now.

Android Development: Starting a server socket

As you already know the application i’m building is using service discovery to connect to other devices. How does this work?

Step 0:  Add activity as observer to the servicehelper class (line 4)

Step 2: Start registering the service to the network (10)

protected void onResume() {

		Log.d(TAG, "On Resume called");
		ServiceHelper.getInstance(this).addObserver(this);
		if (!ServiceHelper.getInstance(this).hasServiceRegistered(
				StrategoService.SERVICE_NAME, StrategoService.SERVICE_TYPE)) {

			ServiceHelper sh = ServiceHelper.getInstance(this);
			try {
				sh.registerNewService(StrategoService.SERVICE_NAME,
						StrategoService.SERVICE_TYPE);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		super.onResume();
	}

Step 3: If service has been registered successfully update ui and start a server socket that waits for any connection. (line 19)

	@Override
	public void update(Observable observable, Object data) {
		if (data instanceof Notifier) {
			Notifier n = (Notifier) data;
			switch (n.toString()) {
			case Notifier.SERVICE_REGISTRATION_SUCCESS:

				
				final TextView text = (TextView) findViewById(R.id.edit_message);
				final NsdServiceInfo info = (NsdServiceInfo) ((Notifier) data)
						.getPayLoad();
				if (text != null) {
					runOnUiThread(new Runnable() {
						public void run() {
							text.setText(info.getServiceName());
						}
					});
				}
				ServiceHelper.getInstance(this).startAndListen();
				break;
			case GameRequestResponseNotifier.REQUEST_CONNECTION:
				// TODO Show dialog
				// Dialog OK send connection_accept response
				IncomingGameRequestDialog dialogCreater = new IncomingGameRequestDialog(this);
				dialogCreater.show(this.getFragmentManager(),TAG);
				
				
				
			default:
				Log.d(TAG, data.toString());
			}
		}
	}

 

Android development about listeners

For my App I need to use service discovery. Service Discovery is a piece of code that lets your android device search for other devices in the same network that can connect to you. But also it gives you the power to generate your own service so other devices can find you.

I wont go into detail about how to setup all this but it involves a lot of callback listeners. Althrough I like the idea of this I dont like the way some people on the internet, who explain this to people who never done this before, implement it. As stated in my previous android blogpost the standard tutorials work with the idea of putting everything in a activity. And well I just dont like that.

So for the service discovery logic and all listeners (3!) that go with it I created a class called ServiceHelper ( if you take a look at the tutorials from android about service discovery they use the same idea ). This helper is a singleton that registers a certain service on the network and works as its own listener for these type of events. So how is this different from the default approach?

The difference comes when I want to let the activity know that something has happened. I’m using the so called Observer/Observable pattern for this. I create my activity. I retrieve an instance of my servicehelper and add myself as a listener to that helper class.

the only thing I need to do next is to add a method ‘update’ so the helper can inform me about what happened. Why I like this idea better? Simple. If an activity implements a RegisterServiceListener, a ResolveListener, a GetMeSomeCoffeeListener the activity gets poluted with all kinds of ‘listener’ methods such as ‘onCoffeeServed’ or ‘onNoCoffeeAnymore’ methods.

Now I only have 1 method update(source, data) and in this update method I can add the logic to handle all the events I’m interested in. I think it makes the code a bit cleaner and easier to understand.