chromecast_vs_hdmi_cableIt’s been some time since Chromecast was launched in Europe and, despite the hype, I cannot find too much advantages over using a simple HDMI cable with a MHL adapter that you plug in your phone’s MicroUSB (mirroring your phone/tablet screen to the TV screen). Here is my comparative, you will decide if is Chromecast worth it.

Chromecast HDMI cable with a MHL adapter
Price 35€ 12€
Wireless Yes No, it’s a wire ;) you need to be near your TV (or a long cable)
Router needed Needs a router with Wifi No
Additional development Apps need to implement specific features to use Chromecast You can view in your TV all that you see in your phone screen
Multi-User Yes You need to unplug the cable and plug it to the another device
Phone charging while streaming Needs to plug a charger to the phone Needs to plug a charger to the MHL adapter
Stream your own content from your phone Yes, but normally with paid applications Yes
You can use your phone/tablet while viewing content Yes No, you see in the TV what you are doing in the phone
Play/pause From your phone From your phone
Screen mirroring With lag With almost no lag

Ok, I didn’t bought a Chromecast yet…

Cuando me invitan a hablar sobre Android o sobre apps suelo siempre comentar algo de monetización y saco este gráfico:

vender_app_europa

Y como siempre genera bastante interés y es lo mas twitteado y a lo que mucha gente le saca fotos, voy a explicar de dónde salen estos datos.

Partiendo de que el usuario paga 1€ por la aplicación:

  • Primero se le quita el IVA, un 21% cuando se vende en Europa desde España. Si vendes fuera de Europa no se aplica IVA, por lo que el gráfico mejoraría un poco, pero sigamos con el caso de Europa.  Tenemos que 1€/1.21 = 0,8264€, por lo que 0,1735€ son de IVA. El IVA se quita antes que la comisión de la appstore.
  • Luego vienen Apple o Google y cogen su comisión, un 30% en ambos casos, por lo que el gráfico es válido para apps tanto Android como iOS. Entonces 0.8264€ x 0,3 = 0,2479€, y nos quedan 0,5785€
  • Y ahora están los pagos a la Seguridad Social y a la Agencia Tributaria. Variarán en función de la base de cotización y el volumen de facturación, pero estimando que anda sobre un 30%, es 0,5785€ x0,3 = 0,1735€
  • Entonces al desarrollador le queda 0,5785€ – 0,1735 = 0,4050€. Vamos, 40 céntimos, y aún habría que quitar inversión en equipos, alquiler de oficina, electricidad, etc.

Lo curioso es que pasa algo parecido si tienes un kiosco y vendes Chupa-Chups. Poca gente es consciente de los costes que conlleva vender o realizar cualquier actividad económica.

Para más temas fiscales sobre vender apps os recomiendo mi artículo Vender en Google Play desde España.

Puedes comentar este post en Google+.

mobile_appsSé que esto es tirar piedras contra mi propio tejado ya que yo me gano la vida gracias sobre todo a aplicaciones Android, pero no puedo dejar de pensar que el fenómeno de las apps móviles me recuerda a lo que pasaba hace 10 años en los ordenadores de escritorio, cuando teníamos que descargar una aplicación para Windows, otra para Mac… substitúyase esto por Android, iOS y Windows Phone… sí señor, aplicaciones de escritorio, ¿a que suena rancio?

¿Y por qué Google, que se supone tiene a los mayores expertos en web del mundo apoyó Android cuando tenía un sistema operativo basado en web como ChromeOS? Para mi la respuesta es que la web móvil no estaba preparada y los navegadores móviles no conseguían la suficiente potencia para simular una experiencia nativa. Y es que a día de hoy Android, mejor dicho, la máquina virtual java (JVM) Dalvik, sigue consiguiendo mejor rendimiento que los motores HTML5 móviles (que yo considero también máquinas virtuales), y aunque éstos mejoran día a día, debido a las limitaciones de Javascript (JS) es muy difícil que se aproximen al rendimiento de una JVM.

También podría ser que la mejora de las CPUs móviles haga que no importe el menor rendimiento de las aplicaciones web.

Y está el moviento extraño de Google con Dart. JS es malo, pero… ¿crearte un lenguaje nuevo tú sólo? ¿sin contar con ninguno de los otros actores? Google ya parece Microsoft en sus mejores tiempos ¿recordáis del malogrado VBScript para HTML? Puede ser que la gente de Google sí crea que el futuro está en la web, pero no con JavaScript.

Por otra parte estoy viendo decepcionado como Google se resiste a integrar la Chrome Webstore en Google Play, privándonos de poder publicar aplicaciones HTML5 para Android directamente (sin recurrir a chapuzas como PhoneGAP), también veo cómo Google y Apple siguen proporcionando WebViews del paleolítico capando APIs tan esenciales como WebGL ¿Y por qué? ¿Acaso abrir las puertas a las aplicaciones HTML5 es matar la gallina de los huevos de oro de las apps? Alguien en Cuppertino y en Mountain View debe pensar que sí.

Y aquí entra el, de momento fracasado, FirefoxOS. La gente de Mozilla sí ve claro el futuro en la web. FirefoxOS no es más que un Android al que le cambian la JVM Dalvik por el motor HTML5 Gecko. Tampoco me parece que FirefoxOS tenga mucho sentido ya que es más fácil instalar Firefox en cualquier dispositivo Android y se tiene igual acceso a todas las aplicaciones del Firefox Marketplace. Sin embargo, Firefox con su Marketplace es, en mi opinión, la mejor forma de distribuir y ejecutar aplicaciones HTML5 en un móvil. Pero Firefox está disponible sólo en Android, las políticas de Apple impiden explícitamente usar motores web que no sean el suyo, de nuevo… ¿miedo a las aplicaciones HTML5?

En los últimos 10 años hemos visto como las aplicaciones web substituían a muchas de las aplicaciones que usábamos cada día en nuestros equipos de escritorio, ¿sucederá esto con las apps móviles? Pues no lo sé, dejemos esto de adivinar el futuro para los programas nocturnos de las televisiones.

Puedes comentar este post en Google+.

gradle_logoThe new Android build system is based in Gradle, an advanced build tool that simplifies build automation.

I used Maven for many years and Gradle project structure is very similar, but Gradle configuration files are Groovy-based and much (much!) more simple. Here is the official documentation

This week I migrated a lot of my Android and GWT projects to Gradle (some of them in my github), and here are some tips that I discovered (and I will add more as I find them):

Embrace the new Source Structure

Initially can be difficult, but putting the code under /src/main/java/, Android resources in /src/main/res/, etc. is a very popular form to organize the code. You can configure the build.gradle file to keep the old Android project structure, but I suggest migrating to the new structure.

Reference Another Project in your Workspace

You have two options:

  1. Use a Multi-Project Build
  2. Install the artifact (JAR if is a standard Java library, AAR if an Android Library) in your local Maven repo

Both options are explained below:

Use Multi-Project Builds

You can create a multi-project setup with projects on subfolders adding a settings.gradle file at the root with a include statement:

include 'library-project', 'your-project'

Then inside a your-project’s build.gradle you can easily add a dependency to another project (called “other_project”):

dependencies {
    compile project(':library-project')
}

Sample here.

Install a JAR to your Local Maven Repo (with the source code)

With standard java libraries and a build.gradle file like:

apply plugin: 'java'
apply plugin: 'maven'
group = 'com.company'
version = '0.8'

You can do “gradle install” to copy it yo your Maven repo.

Manually Install a JAR to your Local Maven Repo (without source code)

At the moment a lot of Google artifacts (=JARs, AARs) are not available at the Maven Central repo, but you can install them manually to your local Maven repo

mvn install:install-file -Dfile=android-support-v4.jar -DgroupId=com.google -DartifactId=android-support-v4 -Dversion=0.1 -Dpackaging=jar

You can also do it with gradle, but it is a bit more complex sample here.

Reference an Artifact from your Local Maven Repository

Be careful to add mavenLocal() to your repositories in the build.gradle:

repositories {
    mavenLocal()
}

Then use a normal reference, for the android-support-v4.jar sample above, it will be:

dependencies {
    compile 'com.google:android-support-v4:0.1'
}

Install an AAR to the Local Maven Repository

AAR is the new package format for Android Libraries. The “gradle install” task (that should install the AAR in the local Maven repository) does not works as expected in those projects, so I use a little hack:

apply plugin: 'maven'
uploadArchives {
  repositories {
    mavenDeployer {
      repository url: 'file://' + new File(System.getProperty('user.home'), '.m2/repository').absolutePath
    }
  }
}
task install(dependsOn: uploadArchives)

Usage sample here.

Android Library Projects need an Application Tag

This is an ADT bug, and the workaround is to add an empty application tag yo your library’s AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" ...>
    <application />

Include all the JARs in the libs/ Directory

This was the default behaviour of Android Projects, to maintain it you can add to your build.gradle:

dependencies {
    compile fileTree(dir: 'libs', include: '*.jar')
}

I suggest referencing local JARs only in final Android projects, referencing them in libraries can cause problems, read below:

Avoid Referencing Local JARs in Android and Java Libraries

If you reference local JARs in Android libraries, those jars are going to be embedded in the AAR. If you reference again the JAR from a project that uses the AAR you will see this build error:

:project:dexDebug
UNEXPECTED TOP-LEVEL EXCEPTION:
java.lang.IllegalArgumentException: already added: Landroid/support/v4/app/ActivityCompatHoneycomb;
//..
1 error; aborting
:project:dexDebug FAILED

If an Android Library projects references a JAR library, and the JAR library references local JAR files, those local JAR files are not going to be embedded in the Android projects using the library.

The best solution is to install all the JARs to your local Maven repo as explained above.

Or Embed all the Dependency JARs Into your Library

In some situations you may embed all the JARs in your library, but ONLY if those dependency JARs are not going to be referenced again in a project that uses the library.

jar {
    from configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
}

Android Projects Need Libraries Compiled with Java 1.6

If in an Android Project you use a library JAR including classes compiled with source compatibility to Java 1.7, build gives this WARNING:

trouble processing:
bad class file magic (cafebabe) or version (0033.0000)
...while parsing Class

…and the class is not included in the APK, so the app force closes at running.

This may be solved adding in the build.gradle of the library:

apply plugin: 'java'
sourceCompatibility = 1.6
targetCompatibility = 1.6

Create a Source JAR for a Library

Source JARs are needed for libraries used in GWT projects. To generate them add this to your build.gradle:

apply plugin: 'maven'
//...
task sourcesJar(type: Jar, dependsOn:classes) {
    classifier = 'sources'
    from sourceSets.main.allSource
}
artifacts {
    archives sourcesJar
}

You can install them to your local repo with “gradle install”

Include a Source JAR from Another Project

For multi-project_builds:

dependencies {
    compile project(':other_project')
    compile project(path: ':other_project', configuration: 'archives')
}

Sample here.

Include a Source JAR from a Maven Repo

Simply append “:sources”:

dependencies {
    compile 'com.company:artifact-name:0.8'
    compile 'com.company:artifact-name:0.8:sources'
}

screenshotGetting back to the old days where I used Emacs to code (ok, more than ten years ago), now I’m using a dark theme in Eclipse. Dark themes are less eye-stressing and now are becoming popular with editors like IntelliJ, Sublime Text and the last Visual Studio. But Eclipse is not so easy to setup in dark colors…

The Eclipse Juno platform supports styling of the SWT widgets via CSS, but many other elements must be setup manually, so I published my CSS and setup instructions in a GitHub repository: https://github.com/albertoruibal/eclipse_dark_css

Welcome to the dark side!

chromiumHTML5 is a fantastic app framework, but there are many environments where you cannot rely on the features support of the browser (specially when dealing against Internet Explorer, old windows versions or environments where you cannot freely upgrade the browsers). Recently I found this problem trying to package Mobialia Chess 3D for Windows 8. Microsoft provides some tools to package HTML apps to native apps, but they will run with the Internet Explorer engine, lacking features like WebGL, WebRTC, etc.

Chromium Embedded Framework (CEF) is a library that allows to embed a Chromium webview in your native Windows or Mac desktop application. So you can convert any HTML5 to a traditional desktop app (and I bet some users to try guessing if Mobialia Chess 3D is an HTML5 app). You can also create a Windows/Mac installer to  distribute the app (I used InnoSetup, but this is another story…).

Using CEF requires a small knowledge about Windows/Mac desktop app development. I created a Windows app using Visual Studio Express, it was not very difficult, because CEF includes a “cefclient” sample project that you can use as a template to start your project development.

The main problem that I found was the size, embedding CEF will add 45Mb size to your installed application. I also found other minor problems like the lack of mp3 sound support (due to license problems) solved converting the sound files to ogg.

CEF is already used by great desktop applications like Steam, Evernote or Spotify, so it’s a great option to consider in your developments.

Many people has problems with the Google TV Emulator because it hangs up booting at the Google TV logo. The problem is that it only works with specific device configurations and resolutions.

First you need to install the “GoogleTV Emulation Addon” using the Android SDK Manager. Then, create a new “Device Definition” (notice the new “Device Definition” tab at the top of the Android Virtual Device Manager in the lasts Android SDKs).

When prompted for the device definition parameters you must enter:

googletv1

This setup is for a 720p resolution, for a 1080p you must change the resolution to 1920×1080 and the density from tvdpi to xhdpi. Once the device definition is created, the next step is to create a new Android Virtual Device using it:

googletv2

Et voilà, our Google Tv emulator is up and running:

googletv3

gplus-hangout-60x230-normalThose days I’m working in Mobialia Chess&Chess at ICC with a lot of bug fixes and some new features… and as a side project I developed a “Mobialia Chess 3D” Google+ Hangout Plugin to play 3D Chess inside a Hangout.

You can start a chess hangout pressing the “Hangout” button in http://chess.mobialia.com or directly with the image button in this post. All the participants in the hangout can move the pieces, so it can be used to play video-call chess games or to teach chess lessons.

Technically it wasn’t very hard, the Google+ Hangouts API offers a shared state and notifications when the state changes, you can get all the API information at https://developers.google.com/+/hangouts/

I was thinking to use this API since I saw some hangout API demos by +Paul Kinlan at the BCN DevFest 2011, and recently  I had the final idea watching a Quobis WebRTC webinar.

I had only problems accessing frames from different domains, (prohibited to avoid Cross-Site-Scripting, XSS, attacks) because the hangout is hosted in a Google domain and the chess app in a different one.

To bypass those problems I used the HTML5 window.postMessage() API to send and receive messages between frames. You can send messages to frames in other domains passing two parameters to postMessage(): the message and the domain of the receiving frame:

<script type="text/javascript">
var message = "";
document.getElementById('iframeid').contentWindow.postMessage(message, "http://www.domain.com");
</script>
<iframe id="iframeid" height="100%" width="100%" src="http://www.domain.com/iframe.html"></iframe>

and in the receiving frame you must set a message listener:

window.addEventListener("message", function messageReceived(evt) {
    console.log("Receiving message from " + evt.origin + " : " + evt.data);
    //...
}

Note that you receive the origin domain, crucial because the domain of the hangout is different each time.

The future is here, and JavaScript (JS) is everywhere, but JS development is so hard that many people prefer to develop in other languages and then compile their code to JS, using JS as a universal runtime. Here are the most interesting options:

GWT

GWT stand for Google Web Toolkit, but now it’s in hands of the community and extensively used in many corporations. GWT compiles Java into JS and it’s strongly optimized. I use it a lot, and I feel very productive using an advanced IDE like Eclipse with tools like code assist, refactor, etc.

https://developers.google.com/web-toolkit/

CoffeeScript

A very compact language, inspired by Ruby and Python and that has become extremely popular in the last years. I’m not very familiar with the “Syntactic sugar” and I’m more productive with traditional languages (yes, I love curly backets! {}).

http://coffeescript.org/

Haxe

If you are an ActionScript developer (Adobe Flash), this is your language. It not only compiles to JS and ActionScript, also to PHP, C++, C#, etc. It’s becoming popular for the development of multi-platform mobile games with NME.

http://www.haxe.org/

Dart

This is a new language for the web pushed by Google. It tries to be a “modern and structured” language for the web that can be run directly into the browser, but to retain compatibility (and to run in other browsers that publicly rejected Dart), it can also be compiled to JS.

http://www.dartlang.org/

List of languages that compile to Js: http://altjs.org/

Ok, I’m supossed to be an Android developer, but i’m going back to HTML+JS for some projects, and I found that HTML5 has really powerful new APIS, these are my favourite:

  1. WebGL: Is changing the game rules, finally advanced 3D graphics in the browser. As it’s very hard to use directly,  I suggest the Three.js library
  2. Storage: A very simple system so store data in the browser, much more powerful than cookies
  3. Web Workers: Multithreading in Javascript, yes, now it’s possible
  4. WebAudio: a good sound API for the web, continues having some differences between browsers, but promises to be great

And I am already using this APIs in some Mobialia web apps:

App WebGL Storage Web Workers WebAudio
Mobialia Chess 3D X X X
Slot Racing X X X
Four in a Row X X

This apps are developed in Java with Google Web Toolkit (GWT), you can also view  my slides: Migrating apps from Android to HTML5 via GWT.