Sunday, July 28, 2013

Check if the device has Internet

On many platform, and specifically on mobile devices, there is a constant need to know if there is a connection to the internet (or the outer world).

I've seen countless Android implementations, trying to figure and configure the network states, attempting to understand if the underline network can access the outer world or not, I've also wrote one... :(

Thing about all these implementations, they all fail the scenario where the device is connected to a network, which is not connected to the outer world, for example a router which is not connected to the wall...

Today, I bring you a very simple very easy way to perform this check:

private void checkWebConnectiity()
  throws IOException {
 Socket socket = null;
 try {
  socket = new Socket("", 80);
 } catch (IOException e) {
  throw e;
 } finally {
  if (socket != null)
   try {
   } catch (IOException e) {
    logWarning("Ignoring...", e);

This covers most of the cases you would need, and is an absolute check, to whether or not you have access to the internet.

You can also return a boolean for your satisfaction, I required an exception to determine the cause of error...

Saturday, February 2, 2013

JavaFX in a Swing application

I've tried multiple libraries to play audio before settling with JavaFX, and they all sucked. These were not intuitive, and not easy to operate.

JavaFX on the other hand, is simple quick and does the work elegantly. There are a few issues I have with their design such as:

  • No exception throwing!!!
  • When playing media there are three threads been created and destroyed rapidly, for the entire duration of the playing. (WTH???)
In any case, I've needed a way to play my audio files but I didn't like this sort of API, so I've wrapped it with my own interfaces and all, but then I've learned that JavaFX needed to be initialized or it would throw:

java.lang.IllegalStateException: Toolkit not initialized

So... here is what you need to do:

 private void initJavaFX() {
  final CountDownLatch latch = new CountDownLatch(1);

  new Thread(new Runnable() {

   public void run() {
    JFXPanel p = new JFXPanel();
  }, "JavaFX-initializer").start();
  try {
  } catch (InterruptedException e) {

This would initialize JavaFX framework, and allow you to play media...