Java – Blocks used in iOS need to be converted to Android Java code

Blocks used in iOS need to be converted to Android Java code… here is a solution to the problem.

Blocks used in iOS need to be converted to Android Java code

I want to start using blocks in my iPhone apps because they’re really handy.

However, since all applications also have to be ported to Android Java, I’m not sure if this is a good idea because I don’t know how to easily convert these blocks.

So far, porting iOS to Android has been straightforward, almost line by line – but how does the iOS block translate to Java? (I’m not talking about Java blocks, of course.)

Thank you very much!

Solution

Java allows anonymous (unnamed) classes. What’s more, they can extend another class. When used in this way, they are similar to blocks in Objective C.

You’ll often see an anonymous class defined, which implements Runnable or something similar. This is doing something similar to a block: providing an anonymous, inline code definition that is passed somewhere for later use.

For more information, see the example here:
http://en.wikipedia.org/wiki/Closure_%28computer_science%29#Local_classes_.28Java.29

So in Java you can write something like this:

doMyThing(new Runnable() {
  void run() {
      your 'block' code here
  }
});

The doMyThing method can call the run method later (or generate it as a thread by passing Runnable to a new Thread object, etc.).

Further discussion here:

Limitations of Java Anonymous Classes compared to Objective-C Blocks

http://www.jondev.net/articles/Objective-C_blocks_vs_Java_Anonymous_Classes_or_Functions_(callbacks)

Related Problems and Solutions