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());
			}
		}
	}

 

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.