- The Google Services Gradle Plugin
- Introduction
- Adding the JSON File
- Processing the JSON File
- Troubleshooting
- Как импортировать com.google.android.gms. * В Android Studio с помощью сборки Gradle?
- Set up Google Play services
- Declare dependencies for Google Play services
- Check whether Google Play services is installed
- Google Play services dependencies
- Gradle plugins
The Google Services Gradle Plugin
Introduction
As part of enabling Google APIs or Firebase services in your Android application you may have to add the google-services plugin to your build.gradle file:
The google-services plugin has two main functions:
- Process the google-services.json file and produce Android resources that can be used in your application’s code. See Adding the JSON File more information.
Add dependencies for basic libraries required for the services you have enabled. This step requires that you apply the Google Services Gradle plugin in your app/build.gradle file, like so:
apply plugin: ‘com.google.gms.google-services’
You can see the result of this step by running ./gradlew :app:dependencies .
Adding the JSON File
The google-services.json file is generally placed in the app/ directory (at the root of the Android Studio app module). As of version 2.2.0 the plugin supports build type and product flavor specific JSON files. All of the following directory structures are valid:
Note: Providing a google-services.json file in the release directory allows you to maintain a separate Firebase project for your production APKs.
When product flavors are in use these more complicated directory structures are also valid.
Processing the JSON File
The google-services.json file has the following basic structure:
The project_info object contains general information about your project, while each member of the client array contains information about the clients (Android apps) that you have added to the project.
When processing the JSON file for your Android app, the plugin only uses the client object that matches your package name (for the current build type) based on the following logic:
- For each member of the client array:
- Check the value of client_info/android_client_info/package_name
- If the package name matches this value, return the member object.
- If none of the members of client match the package name, an exception is thrown.
For the rest of this document we will use
The main result of the JSON processing is to produce two XML files which you can reference as Android resources in your Java code. Below is an example of each file:
app/build/generated/res/google-services/
app/build/generated/res/google-services/
Every value in the XML files is present in the google-services.json file at the locations below. If your Android project has some configuration that prevents you from using the google-services plugin, you can safely recreate the XML files manually using these values:
google_app_id:
gcm_defaultSenderId:
default_web_client_id:
ga_trackingId:
firebase_database_url:
google_api_key:
google_crash_reporting_api_key:
project_id:
Troubleshooting
Q: When building I get the following error message: «File google-services.json is missing from module root folder. The Google Services Plugin cannot function without it».
A: The Firebase console will help you download the google-services.json . In addition, the Quickstart guides for most APIs have instructions for generating this file. Once you have downloaded the google-services.json file, copy it into the app/ folder of your Android Studio project, or into the app/src/
Q: I can’t find the symbol «R.string.gcm_defaultSenderId», «R.xml.global_tracker», etc.
A: Make sure the package name in your build.gradle file matches the package name you entered when creating the google-services.json file. If you are not sure, run through the getting started flow again and get a new json file.
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Источник
Как импортировать com.google.android.gms. * В Android Studio с помощью сборки Gradle?
Я выполнил процедуру, описанную здесь: « Настройка» Я нажал кнопку «Синхронизировать проект с помощью Gradle». Gradle и Android Studio, похоже, все находят, но тогда я не могу использовать код gms. Если я попытаюсь импортировать, я получу автозаполнение для com.google.android.gms, но не буду дальше. Я обновил все пакеты с помощью Android SDK Manager.
- Я запускаю Android Studio 0.4.2.
- Мой minSdk установлен в 9
- My build.gradle включает компиляцию ‘com.google.android.gms: play-services: 4.0.30’
Что касается этой процедуры, я должен быть готов к кодированию, но это просто не работает. Есть идеи?
[Изменить, добавлена информация]
Я могу найти файл ComGoogleAndroiddGmsPlayServices3265.aar в моем каталоге взорванных пакетов. Внутри этого файла я также нахожу общий каталог и внутри, что я нахожу GooglePlayServicesUtil.class (это то, что не найдено в моем приложении)
Проблема не специфична для Google Play Services или Android Studio. Я попробовал добавить другую библиотеку (HoloColorPicker) и имел те же результаты. Тем не менее, я смог добавить ресурсы библиотеки в свой проект! Я смог добавить их в свои макеты XML и просмотреть их в своем приложении. Я смог взаимодействовать с ними, они отлично работали. Проблема возникла снова, когда я попытался ссылаться на них в коде. Точно так же, как в случае с gms, у меня было завершение кода при попытке импортировать до точки фактического класса, и я не смог объявить класс в коде.
Я смог использовать библиотеку, клонируя ее и импортируя проект.
Кроме того, это не проблема Android Studio, потому что то же самое происходит в командной строке с «./gradlew clean build»,
Это текущая ошибка в Android Studio: https://code.google.com/p/android/issues/detail?id=64508, которая будет исправлена на этой неделе.
Обходной путь заключается в том, чтобы закрыть проект, удалить файлы .iml и проект .idea и повторно импортировать проект.
Храните свой compile ‘com.google.android.gms:play-services:4.0.30’ качестве первой строки в зависимостях build.gradle, таких как
Откройте «Файл»> «Структура проекта» и выполните следующие действия.
Выберите основной модуль, в который вы хотите добавить зависимость, и нажмите «ОК».
Теперь попробуйте импортировать.
Я думаю, что самый важный вопрос – это то, чего вы хотите достичь. Не весь код находится под этим пакетом. Даже не уверен, какой из них.
Как отмечалось ранее, это ошибка с Android Studio. Он просто не распознает путь для классов и показывает, что вам нравится, если есть ошибка. Если вы попробуете компиляцию, вы увидите, что все работает нормально.
Недавно гоуглер сказал, что он будет рассмотрен на этой неделе, поэтому будьте терпеливы и давайте посмотрим, что произойдет.
Тот факт, что AS находится в режиме предварительного просмотра, говорит нам, что такие вещи будут происходить 🙂
Думаю, Android-студия сумасшедшая. Он удаляет функцию «Импорт модуля», и вы можете делать только «Новый модуль». Если вы разрабатываете Eclipse, вам нужно экспортировать все свои проекты в Gradle, прежде чем переключиться на студию Androids (WTF?)
Я предпочитаю « IntelliJ IDEA Community Edition », хотя это аналогичная студия Android, но это лучше, чем Android-студия (по крайней мере до сих пор). Вы просто импортируете проект как формат eclipse, IntelliJ IDEA автоматически обнаружит библиотеки зависимостей (возможно, вам нужно вручную импортировать библиотеки jar) и перестроить проект. Это сделано.
Источник
Set up Google Play services
To develop an app using Google Play services APIs, follow the instructions on this page to set up your project with the relevant SDKs, which are available from the Google maven repository.
To test your app when using Google Play services, you must use one of the following:
- A compatible Android device that runs Android 4.4 (API level 19) or higher and has the Google Play Store app installed.
- The Android emulator with an AVD that runs the Google APIs platform based on Android 4.4 (API level 19) or higher.
Declare dependencies for Google Play services
To develop features that depend on the Google Play services APIs in your app, complete the following steps:
Open the build.gradle file inside your app’s module directory.
For each SDK that your app requires, include the dependency for that SDK. This page includes a section that lists common Google Play services dependencies for Android apps. You might also want to add Firebase dependencies to your project.
Save the changes and sync your project.
The following snippet shows an example build.gradle file that uses the location library:
New versions of the Google Play services SDKs with bug fixes and new features are periodically released. These updates are announced in the release notes. If your app uses a dependency that has been updated, change to the latest version in your app’s dependencies to take advantage of these fixes.
Check whether Google Play services is installed
As described in the Google Play services overview, Google Play services receives automatic updates on Android 4.4 (API level 19) and higher through the Google Play Store app. However, Android devices without Google Play Store don’t have Google Play services installed. If your app runs on devices without Google Play services, you might want to check to see if Google Play services is installed on the device before you attempt to use Google APIs, or enable features in your app that require Google Play services to function.
To check for the presence of Google Play services on the device, use the isGooglePlayServicesAvailable() method.
To then begin a connection to Google Play services, or learn how to detect whether the version of Google Play services installed supports a specific API, read the guide on Accessing Google APIs.
Google Play services dependencies
The following table lists the dependencies for Google Play services that you can include in your Android app. You can filter the list by device type by selecting one of the buttons, and you can search for a specific use case or dependency name by entering text into the box that appears after the buttons.
Phones and Tablets Android TV Auto Android Go Chrome OS Wear OS
Use case and dependency name | Supported devices |
---|---|
Google Mobile Ads com.google.android.gms:play-services-ads:20.5.0 | Phone, Tablet |
Android Advertising ID (AAID) com.google.android.gms:play-services-ads-identifier:17.1.0 | Phone, Tablet, Android TV, Chrome OS |
Lightweight version of Google Mobile Ads com.google.android.gms:play-services-ads-lite:20.5.0 | Phone, Tablet |
AdSense for Search (AFS) Custom Search Ads (CSA) com.google.android.gms:play-services-afs-native:19.0.1 | Phone, Tablet, Chrome OS |
Google Analytics Services SDK for Android com.google.android.gms:play-services-analytics:17.0.1 | Deprecated. Use Google Analytics for Firebase instead. |
Android App Set ID com.google.android.gms:play-services-appset:16.0.0 | Phone, Tablet, Android TV, Chrome OS |
Google Sign-In for Android com.google.android.gms:play-services-auth:19.2.0 | Phone, Tablet, Android TV, Auto, Android Go, Chrome OS |
SMS Retriever API com.google.android.gms:play-services-auth-api-phone:17.5.1 | Phone, Tablet, Android Go |
Block Store API (includes user credential storage) com.google.android.gms:play-services-auth-blockstore:16.0.2 | Phone, Tablet, Android Go, Chrome OS |
Google Awareness API com.google.android.gms:play-services-awareness:18.0.2 | Phone, Tablet, Auto, Android Go, Chrome OS |
Utility classes com.google.android.gms:play-services-base:17.6.0 | Phone, Tablet, Android TV, Auto, Android Go, Chrome OS, Wear OS |
More utility classes com.google.android.gms:play-services-basement:17.6.0 | Phone, Tablet, Android TV, Auto, Android Go, Chrome OS, Wear OS |
Google Cast com.google.android.gms:play-services-cast:20.1.0 | Phone, Tablet, Android Go, Chrome OS |
Google Cast Application Framework (CAF) com.google.android.gms:play-services-cast-framework:20.1.0 | Phone, Tablet, Android Go, Chrome OS |
Chromium network stack (Cronet) com.google.android.gms:play-services-cronet:17.0.1 | Phone, Tablet, Android TV, Auto, Android Go, Chrome OS, Wear OS |
Fast IDentity Online (FIDO) Authentication com.google.android.gms:play-services-fido:19.0.0-beta | Phone, Tablet, Android TV, Auto, Android Go, Chrome OS, Wear OS |
Supported on devices that run Android 7.0 (API level 24) or higher.
com.google.android.gms:play-services-fitness:20.0.0
com.google.android.gms:play-services-games:21.0.0
com.google.android.gms:play-services-instantapps:17.0.1
Supported on devices that run Android 5.0 (API level 21) or higher.
com.google.android.gms:play-services-location:18.0.0
com.google.android.gms:play-services-maps:18.0.0
com.google.android.gms:play-services-mlkit-barcode-scanning:16.2.1
com.google.android.gms:play-services-mlkit-face-detection:16.2.0
com.google.android.gms:play-services-mlkit-image-labeling:16.0.5
com.google.android.gms:play-services-mlkit-image-labeling-custom:16.0.0-beta1
com.google.android.gms:play-services-mlkit-language-id:16.0.0-beta2
com.google.android.gms:play-services-mlkit-text-recognition:17.0.0
com.google.android.gms:play-services-nearby:18.0.0
com.google.android.gms:play-services-oss-licenses:17.0.0
Supported on devices that run Android 5.0 (API level 21) or higher.
com.google.android.gms:play-services-password-complexity:17.0.1
Supported on devices that run Android 4.4 (API level 19) to Android 9 (API level 28).
com.google.android.gms:play-services-pay:16.0.1
Supported on devices that run Android 5.0 (API level 20) or higher.
com.google.android.gms:play-services-recaptcha:16.0.1
com.google.android.gms:play-services-safetynet:17.0.1
com.google.android.gms:play-services-tagmanager:17.0.1
com.google.android.gms:play-services-tasks:17.2.1
com.google.android.gms:play-services-vision:20.1.3
com.google.android.gms:play-services-wallet:18.1.3
com.google.android.gms:play-services-wearable:17.1.0
Gradle plugins
Google Play services also includes several Gradle plugins, as shown in the following table. Note that the buttons that appear before the previous table don’t change the information that appears in this table.
Use case and Gradle plugin name | Supported devices |
---|---|
Show open-source licenses com.google.android.gms:oss-licenses-plugin:0.10.4 | Phone, Tablet, Chrome OS |
Strict version checking com.google.android.gms:strict-version-matcher-plugin:1.2.2 | Phone, Tablet, Android TV, Auto, Android Go, Chrome OS, Wear OS |
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Источник