jueves, 18 de febrero de 2016

Entre fuego cruzado: Admob vs Google Play Services y sus problemas | Crossfire: Admob vs Google Play Services problems



La batalla por actualizar mi primer juego
Como dicho en las entradas anteriores, lo siguiente en mi lista era realizar la primera actualización a mi primer juego Infinite Squared Run, las soluciones a los problemas estarán sobre el final.



                                                                  Español | English

El plan inicial era simple: Integrar el servicio "Google Play Services" (que viene un plugin para Unity), arreglar un par de bugs o cosas que les molestaron a los jugadores y listo. Por lo que modificar unos datos y poner "importar paquete / Aceptar" pero mi sorpresa fue cuando luego de compilar y que arranque el juego, al darle click al botón de inicio, este daba un error: "La aplicación Infinite Squared Run se ha detenido".

Voy corriendo a la PC y pongo Play desde Unity para probar el juego, si bien las funciones de Mobile no iban a andar, si el juego en sí tenía un error, debía saltar. Para agregar dificultad, desde la PC pude jugar perfectamente, sin ningún problema, ni error ni advertencias. Ahí es cuando con la peor cara me di cuenta que rompí mi juego, me quede analizando que cosas había hecho así las podía des-hacer, repasando mi "historial de cosas que hice" en mi cabeza, me doy cuenta que  lo que modifique en el script de Character_Controller (script principal que maneja la mayoría de las mecánicas (aunque no necesariamente las más importantes)) no era el problema. Por lo que el error era y no era mío, era mío en el sentido de que algo mal toqué, pero no era mío sabiendo que no era mi código el que presentaba problemas sino la nueva implementación del plugin de Google.

Luego de incontables compilaciones, test, pruebas de todo tipo: eliminando código, agregando, modificando. Llegue a un punto medio vació en el que me rendí por un momento y tome la decisión de des-instalar los plugins e instalarlos de nuevo desde 0. A lo que a las carpetas de los plugins y la carpeta misma llamada "plugins" de mi proyecto de Unity las copié y las meti en una carpeta fuera del proyecto llamada "Corrupted" y volvi con Admob. Una vez implementado Admob y testeado había vuelto al paso inicial, como estaba antes de empezar, pero ahora con la precaución necesaria de copiar el plugin y su carpeta "plugin" afuera del proyecto y guardarlo en una carpeta llamada "Backup", así en caso de errores inesperados, siempre podré volver a la versión funcional (Cosa que debí haber hecho como paso 1 antes de hacer todo esto, pero creo que es otra lección aprendida).

Ya habiendo instalado y des-instalado varias veces llegando a errores inesperados mezclados con intentos raros de esperanza por parte de la aplicación en donde por ratos decidía funcionar perfecto y después dar error. Decidí buscar en Google el problema, lo que lleva al nombre del título: al buscar en Google "conflictos entre Admob y Google Play Services" descubro un montón de entradas de gente con la misma problemática con la mía, ahí me di cuenta que lo que parecía sencillo, resulto ser como correr por un campo a fuego cruzado ya que inocentemente me metí en un problema grande, ya que Admob y Google Play Services tenían reputación de ser incompatibles y de generar muchos problemas aleatorios.

Nota: Muchos de estos problemas podría haberlos visto desde otra perspectiva si tuviera mi equipo bien adecuado, refiriéndome en especial a que mi celular Moto G no se puede conectar a la PC, por lo que para instalar cada compilación, debía subir el APK a Mega para bajarlo a mi celular, instalarlo y de ahí si tira un error (lo cual no especifica) adivinar que es lo que lo causaba. Si tuviera el celular conectado listo para el "Build and Run" de Unity, podría haber visto en la consola los errores y también ahorrado el tiempo en el que el APK subía a Mega y yo lo descargaba.


De tanto buscar en Google y Youtube alguna solución o tutorial, encuentro uno que es justamente para mi problema, con el título algo así como "Implementar Admob y Google Play Services con Unity 5.x"para el cual no dudé en clickear y ver, luego de hacerle caso a cada paso a paso, compilo. Espero. Error. A partir de acá por parte del video y de otros  foros me entero de la relevancia del Android Manifest.xml . Este archivo, para el que no sabe mucho, es esencial para cualquier creación o proyecto de Android.  Lo que hacen los plugin tanto de Admob como el Google Play Services es agregarle código a su configuración, luego, Unity al compilar junta todo en un solo Android Manifest.xml, se veía que el problema podía, si no era existir ahí, ser uno de los grandes lugares que hacían que la aplicación tuviera errores inesperados.


Hasta que leo un foro que tenía un comentario distinto, uno que me salvo sin que se de cuenta: Admob había actualizado su versión del plugin para Unity a la versión 3.0 (yo contaba con la versión anterior), lo que justamente resolvía esta nueva versión eran los conflictos que tenía Admob con Google Play Services, para lo cual cada vez estaba más feliz. Paso al nuevo plan por etapas: Primero instalar el nuevo Admob, compilar y testar de que funcione. Luego de que todo funcione declaro esta como la "nueva" versión estable, lo único que cambia con la anterior es la versión 3.0 del Admob.

Ahora la parte de terror, implementar Google Play Services, el proceso era el mismo, pero siempre podía fallar por cualquier razón. Importo los paquetes necesarios, compilo. No hay error. En ese momento creí que ya todo esto estaba terminado, subo a Mega como de costumbre para testear en mi celular y cuando lo inicio, Error. Lo único que me quedaba modificar eran los Manifests, digo en plural ya que cada plugin proporcionaba su propio Manifest, así que siguiendo unos consejos de unos foros sobre modificar estos archivos, más que nada sobre las partes de las versiones y quitando la parte de método pago, ya que mi juego es gratis, intento de nuevo con la fe ya perdida y PUM. EL JUEGO ARRANCA. Ya al momento de iniciar nos pide iniciar sesión para Google Play y el momento de tensión, al apretar Start o crasheaba o iniciaba. Escucho la música y el juego empieza a funcionar perfecto, pierdo a propósito para ver y la tabla de puntuaciones se muestra perfecta. Listo, la actualización se puede dar por terminada.

Teorías sobre las soluciones:

  • Los Manifest tenían distintas versiones, Admob decía versión 9 y Google Play Service 8 , cambiando todos los Manifest a versión 9 y con el "Target" a 23 (que es la versión del Android SDK que tengo) me aseguro que todos los Manifest se manejaban sobre las mismas versiones.
  • Una línea de código en el Manifest de Admob si mal no leí es la repetida, era una actividad que empieza comentada como "Google Mobile Ads Activity", esta línea, al estar repetida entra en conflicto.
  • Hablando sobre repeticiones, la causa principal (según varios foros) de la incompatibilidad de estos 2 plugins son archivos repetidos, muchos eran librerías que se repetían dentro de los archivos .jar de cada uno de los plugin, todo esto combinado hacía conflicto.
Los demás errores se solucionaron mágicamente, lo que interpreto es que fue la nueva versión (3.0) del plugin de Admob, que venía con un "Resolver" (JarResolver ) que ya resuelve por sí mismo algunos conflictos.

Así que las instrucciones que le daría a alguien que este en mi anterior situación, de tener Admob y querer implementar GooglePlayServices le recomiendo
  1. Actualizar a la versión 3.0 del plugin de Admob si no lo tenía antes ya
  2. Instalar el plugin de Admob 
  3. Instalar el plugin de GooglePlayServices
  4. Modificar los Manifest para que queden todos hacía la misma versión (yo los deje en 9 que era el que usaba Admob y 23 en vez de 16 o 18 que era la versión de mi SDK de android).
  5. Abrir el Manifest que aparece dentro de la carpeta de /Plugins/Android/GoogleMobileAdsPlugin y quitar estas lineas de código: 
<!-- Google Mobile Ads Activity -->
    <activity android:name="com.google.android.gms.ads.AdActivity"
        android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"/>
  </application>

Para mejores pasos les doy el tutorial de youtube que encontre, esta en español, recomiendo verlo para ver que hacer antes de hacerlo para tener una idea: https://www.youtube.com/watch?v=y2oCGlO9CEk .

De nuevo, una parte de la resolución fue magia y la otra fue sabiendo, por lo que fue una experiencia y unas lecciones para aprender para las próximas actualizaciones de cualquier juego que haga más adelante.

-L



---------------------------------------------------------------------------------

English

The battle for updating my first game
As I have said in the previous posts, the next thing on my list was to do my first Update for my first game Infinite Squared Run, the solutions are near the end




The plan was simple: Implement the services "Google Play Services" (which cames as a plugin for Unity), fix some bugs and things that had bothered some players and done. For which it was "Import package / Accept" but my surprise came when after compiling the build and start the game, when I clicked the "Start" button the game gave an error "Infinite Squared Run has stopped working".

I run into my PC and I play the game from Unity to test the game, although some functions only works on Mobile, if the game itself had an error, it would pop out. But to add some difficulty, on the PC the game worked perfectly, without any problem, I remained analyzing which things I had done so I could un-do them, reviewing my mental "history-of-things-I've-done" I realized that what I modified on the Character_Controller script ( the main script which handles most of the mechanichs( but not for that the most importants)) wasn't the problem. So the problem was and wasn't mine at the same time, in the way that I've done SOMETHING, but it wasn't mine because it wasn't my code the one that has the problems but the new implementation of the plugin of Google.

After countless compilations, test and all kinds of test: eliminating code, adding, modifying. I came to a poit of emptiness on which I gave up for a moment and took the decision of un-installing the plugins and installing them again from scratch. For which I grabbed the folders of the plugins and the folder called "plugins" of my project of Unity and stucked them into a folder outside the project which I called "CORRUPTED" and came back with Admob. Once implemented Admob and after testing it I came to be as I was at the beggining, step 0. But now with the precaution of saving the folder of the Admob plugin and the "plugins" folder outside the project in a folder called "backup", so in case of unexpcted errores, I can always get back to step 0. ( I should have done this before experimenting but now it became a new lesson.)

After installing and un-installing many times getting unexpected errors mixed with weird attempts of hope from the application which sometimes it seemed it worked and then it gave errors. I decided to look up on Google, which gave me the title for this article, after I typed in Google "conflicts between Admob and Google Play Services" and I discover a huge amount of entries from people with the same problems that I had. Then I realized that what I though it was simple, it turned out to be like running throw a field at crossfire as I innocently stepped into a big problem, as Admob and Google Play Services had a reputation of being incompatible with each other also as generating random errors.

Note: Many of theese problems I could have seen them with another perspective if I had my equipment well setup, specially referring to my Moto G cellphone which I can't connect to the PC, so to install every compilation, I needed to upload the APK to Mega to later download it from my cellphone, install it and see from there if an error ocurred (which if it happened, it wouldn't specify why) and then guess why the error happened. If I had the cellphone directly to the PC I could use the "Build and Run" from Unity, see the console for error and save the time it takes the APK to be uploaded every time.

As result of looking up on Google and Youtube any solution or tutorial, I found one that is just for me, with the title as "Implement Admob and Google Play Services with Unity 5.x" (this was in spanish) for which I didn't doubt to click on and watch, after doing everything the man in the video said I compile. Wait. Error. From here on because of the video and some forums I realized the importance of the file Android Manifest.xml . This file, for people who don't understand too much, is essential for any creation or project with Android. What the Admob and Google Play Services plugins do is to add some lines of code to that Manifest, then, Unity when compiling will merge everyone into a single Manifest. It seemed that the problem could, if not live there, be one of the places that made the application to crash.

Then I read a forum which had a different comment, one that saved me without him realizing it: Admob had updated its plugni for Unity to version 3.0 ( I was ussing the previous version), that this new version did was to solve the conflicts between Admob and Google Play Services, which made me every second more happier. So I designed a new Plan: Install the new Admob, compile and test it works fine. Then if this worked properly, I declared this version the "new" stable version, the only thing new is that I'm using Admob v3.0.

Now the scary part, implementing Google Play Services, the process was the same, but it could always failed by any reason. I import the necessary packages, compile. No error. At that moment I thought everything was over, I upload to Mega as usual to test on my phone and when I open the game. Eror. The only thing left to modify was the Manifests, I speak in plurar because each plugin had its own Manifest, so I followed the advice of ome forums about modifying this files, most importantly the part of the versions, taking away the part of "in app purchase" as my game is for ffree and then I tried again with no hope and BAM. THE GAME WORKS. As it loaded it asked us to login to Google Play and the moment of tension. When I clicked Start either the game works or it crashes. I listen to the music and the game starts working perfectly, I let myself die to see the leader board and there it was, perfect. Done, the first Update can be marked as finished
Theories about the solutions:
  • The Manifests had different version, Admob said 9 and Google Play Services 8, changing both to 9 and with the "target version" set to 23 (which is the version of my Android SDK) I make sure all the Manifests worked in the same versions
  • If I didn't mirsread a line, a line of code in the Manifest of Admob starting with the comment "Google Mobile Ads Activity", this line, in case of being repeated, genrated problems
  • Talking about repetitions, the main cause ( according to several forums) the incompatibility of this 2 plugins are repeated files, which a lot of them are libraries that are inside each plugins .jar, all this generated conflict.

Other errors solve themselvs by magic, what I think it was this new version(3.0) of the Admob plugin, which came with a "Resolver" (JarResolver) which resolvs by itself many errors.

Some instructions that I would give to someone that it is currently at my previous situation, of having Admob and wanting to implement GooglePlayServices I recommend:
  1. Updating Admob's plugin to version 3.0 or higher
  2. Install Admob's plugin
  3. Install GooglePlayServices' plugin
  4. Modify the manifest so they all are on the same version ( I left them on 9 that was what Admob was using and 23 instead of 16 or 18 which is my version of the Android SDK)
  5. Open the Manifest inside the folder /Plugins/Android/GoogleMobileAdsPlugin and remove this lines:

<!-- Google Mobile Ads Activity -->
    <activity android:name="com.google.android.gms.ads.AdActivity"
        android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"/>
  </application>

In order to see the steps better I found a tutorial on Youtube (its on Spanish), I recommend watching it if you can in order to see what to do befor doing it.

Again, one part of the solution was magic, the other was knowing, for what it was an experience and some lessons to learn from for future updates of any game I make in the future

-L

No hay comentarios.:

Publicar un comentario