Adding Google Play services to a MobileFirst hybrid Android application in Android Studio

Configure your project to work in Android Studio, add Google Play services, and troubleshoot common errors.

Procedure

  1. In the Android project, open the project.properties file, remove the library reference to the google-play-services library, and save the file
  2. Configure your project so that it works in Android Studio, by following the procedure Converting a MobileFirst project to an Android Studio-based project (for project created either with the MobileFirst Platform Command Line Interface or with MobileFirst Studio), or the procedure Converting a MobileFirst Cordova project to an Android Studio-based project (for MobileFirst Cordova projects).
  3. Follow Google instructions to set up Google Play Services in Android Studio: https://developers.google.com/android/guides/setup.
    Note: Use Google Play services V.8.3.0 when you compile with Android SDK 21 or 22. If you compile with an earlier Android SDK version, you need to use an earlier version of Google Play services.
  4. Sync Gradle and run your app in Android Studio
  5. Optional: Fix possible errors by adding the following three settings to the build.gradle file inside the android{} closure if they are not already present:
    android {
          ...
          defaultConfig {
             multiDexEnabled  true
          }
    
          dexOptions {
             javaMaxHeapSize  "4g"
          }
          packagingOptions {
             pickFirst  'META-INF/ASL2.0'
             pickFirst  'META-INF/LICENSE'
             pickFirst  'META-INF/NOTICE'
          }
          ...
    }
    • com.android.dex.DexIndexOverflowException: method ID not in [0, 0xffff]: 65536.

      multiDexEnabled generates more than one .dex file to handle more than 65,000 methods. For more information, see http://developer.android.com/tools/building/multidex.html.

    • OutOfMemoryError: java.lang.OutOfMemoryError: GC overhead limit exceeded.

      By adding javaMaxHeapSize, you can increase the memory allocation for compiling so many methods.

    • com.android.builder.packaging.DuplicateFileException: Duplicate files copied in APK META-INF/ASL2.0.

      packagingOptions handles duplicate files during the building of the APK. The example code picks the first duplicate files and ignores other duplicates. Other options can also be set instead of the pickFirst option.

  6. Sync Gradle and run your app again.