- Android Development Tutorial. Часть 1/?
- 1. Разработка под Android
- Get Started with Play Games Services for Android
- Before you begin
- App prerequisites
- Set up your game in Google Play Console
- Configure your app
- Sample App Guide
- Step 1: Download the sample app
- Step 2: Set up the game in the Google Play Console
- Step 3: Modify your code
- Step 4: Test your game
Android Development Tutorial. Часть 1/?
Ларс Вогель — евангелист Eclipse.
Под катом Вы обнаружите перевод его статьи, которая описывает процесс создания Android-приложений с помощью Eclipse. Используется Eclipse 3.6, Java 1.6 и Android 2.3 (Gingerbread).
Часть 2
1. Разработка под Android
1.1. Операционная система Android
Android — операционная система, основанная на Linux с интерфейсом программирования Java. Это предоставляет нам такие инструменты, как компилятор, дебаггер и эмулятор устройства, а также его (Андроида) собственную виртуальную машину Java (Dalvik Virtual Machine — DVM). Android создан альянсом Open Handset Alliance, возглавляемым компанией Google.
Android использует специальную виртуальную машину, так званую Dalvik Virtual Machine. Dalvik использует свой, особенный байткод. Следовательно, Вы не можете запускать стандартный байткод Java на Android. Android предоставляет инструмент «dx», который позволяет конвертировать файлы Java Class в файлы «dex» (Dalvik Executable). Android-приложения пакуются в файлы .apk (Android Package) программой «aapt» (Android Asset Packaging Tool) Для упрощения разработки Google предоставляет Android Development Tools (ADT) для Eclipse. ADT выполняет автоматическое преобразование из файлов Java Class в файлы dex, и создает apk во время развертывания.
Android поддерживает 2D и 3D графику, используя библиотеки OpenGL, а также хранение данных в базе данных SQLite.
Каждое Android-приложение запускается в своем собственном процессе и под своим собственным userid, который автоматически генерируется Android-ом во время развертывания. Поэтому приложение изолировано от других запущенных приложений, и неправильно работающее приложение не может беспрепятственно навредить другим Android-приложениям.
1.2. Основные компоненты Android
Android-приложения состоят из следующих частей:
- Activity/Деятельность (далее Активити) — представляет собой схему представления Android-приложений. Например, экран, который видит пользователь. Android-приложение может иметь несколько активити и может переключаться между ними во время выполнения приложения.
- Views/Виды — Пользовательский интерфейс активити, создаваемый виджетами классов, наследуемых от «android.view.View». Схема views управляется через «android.view.ViewGroups».
- Services/Службы — выполняет фоновые задачи без предоставления пользовательского интерфейса. Они могут уведомлять пользователя через систему уведомлений Android.
- Content Provider/Контент-провайдеры — предоставляет данные приложениям, с помощью контент-провайдера Ваше приложение может обмениваться данными с другими приложениями. Android содержит базу данных SQLite, которая может быть контент-провайдером
- Intents/Намерения (далее Интенты) — асинхронные сообщения, которые позволяют приложению запросить функции из других служб или активити. Приложение может делать прямые интенты службе или активити (явное намерение) или запросить у Android зарегистрированные службы и приложения для интента (неявное намерение). Для примера, приложение может запросить через интент контакт из приложения контактов (телефонной/записной книги) аппарата. Приложение регистрирует само себя в интентах через IntentFilter. Интенты — мощный концепт, позволяющий создавать слабосвязанные приложения.
- Broadcast Receiver/Широковещательный приемник (далее просто Приемник) — принимает системные сообщения и неявные интенты, может использоваться для реагирования на изменение состояния системы. Приложение может регистрироваться как приемник определенных событий и может быть запущено, если такое событие произойдет.
Другими частями Android являются виджеты, или живые папки (Live Folders), или живые обои (Live Wallpapers). Живые папки отображают источник любых данных на «рабочем столе» без запуска соответствующих приложений.
1.3. Безопасность и разрешения
Android определяет конкретные разрешения для определенных задач. К примеру, если приложение хочет получить доступ в Интернет, оно должно определить в своем файле конфигурации, что оно хотело бы получить соответствующие разрешения. Во время установки Android-приложения пользователю показывается экран, на котором ему нужно дать приложению требуемые разрешения.
1.4. AndroidManifest.xml
Android-приложения описываются файлом «AndroidManifest.xml». В этих файлах должны быть объявлены все активити, службы, приемники и контент-провайдеры приложения. Также он должен содержать требуемые приложением разрешения. Например, если приложению требуется доступ к сети, то это должно быть определено здесь. «AndroidManifest.xml» можно рассматривать, как описание для развертывания Android-приложения.
Атрибут «package» — базовый пакет для следующих элементов Java. Он также обязан быть уникальным, т.к. Android Marketplace только единожды принимает заявку на каждый «package». Следовательно, хорошей привычкой будет использование Вашего обратного доменного имени как «package», для избежания конфликтов с другими разработчиками.
«android:versionName» и «android:versionCode» определяют версию Вашего приложения. «versionName» — то, что видит пользователь и может быть любой строкой. «versionCode» должен быть целым, и Android Market использует это для определения, предоставили ли Вы новую версию, чтобы запустить обновления на устройствах, на которых установлено Ваше приложение. Как правило. начинается с 1 и увеличивается на единицу, если Вы выпускаете новую версию приложения.
«activity» определяет активити, в этом примере указывает на класс «de.vogella.android.temperature.Convert». Для этого класса зарегистрирован фильтр интентов, определяющий, что это активити запускается при запуске приложения (действие android:name=«android.intent.action.MAIN»). Определение категории (категория android:name=«android.intent.category.LAUNCHER» ) определяет, что это приложение добавлено в директорию приложений на Android-устройстве. Значения со знаком @ ссылаются на файлы ресурсов, которые содержат актуальные значения. Это упрощает работу с разными ресурсами, такими как строки, цвета, иконки, для разных устройств и упрощает перевод приложений.
Часть «uses-sdk» из «AndroidManifest.xml» определяет минимальную версию SDK, на котором можно запускать Ваше приложение. Это предотвращает установку Вашего приложения на устройства с более старой версией SDK.
1.5. R.java, Resources и Assets
Каталог «gen» в Android-проекте содержит генерированные значения. «R.java» — генерированный класс, который содержит ссылки на ресурсы из папки «res» проекта. Эти ресурсы содержатся в директории «res» и могут быть значениями, меню, схемами, иконками или рисунками, или анимациями. Например, ресурсом могут быть рисунок или XML-файлы, содержащие определенные строки.
Если Вы создаете новые ресурсы, то соответствующие ссылки будут автоматически созданы в «R.java». Ссылки являются статическими значениями типа int (целочисленными константами), система Android предоставляет методы доступа к соответствующим ресурсам. Например, для доступа к строке с идентификатором ссылки «R.string.yourString» используйте метод getString(R.string.yourString)); Пожалуйста, не пробуйте изменять «R.java» в ручную.
Тогда как каталог „res“ хранит структурированные значения, известные платформе Android, каталог „assets“ может быть использован для хранения любых данных. В Java Вы можете получить доступ к этим данным через AssetsManager и метод getAssets().
1.6. Активити и Макеты (layout)
Пользовательский интерфейс для деятельности (Activity) определяется с помощью макетов. Во время исполнения макеты — экземпляры «android.view.ViewGroups». Макет определяет элементы пользовательского интерфейса, их свойства и расположение. Элементы UI основываются на классе «android.view.View». ViewGroup — подкласс View. Макеты может содержать компоненты UI (Views/Виды) или другие макеты (ViewGroups). Вам не следует делать большую вложенность дочерних элементов во ViewGroups, так как это влияет на производительность.
Макет может быть определен с помощью Java-кода или с помощью XML. Как правило, используйте Java-код для генерирования макета, если не знаете про содержимое заранее. Например, если Ваш макет зависит от содержимого, которое Вы читаете из интернета.
Макеты, основанные на XML определяются с помощью файла ресурсов в папке «/res/layout». Этот файл определяет группу видов (см. пункт 1.2), виды, их отношения и атрибуты для отдельных макетов. Если элемент UI требует доступа с помощью Java-кода, дайте элементу UI уникальный идентификатор (id) с помощью атрибута «android:id». Для того, чтобы назначить новый идентификатор элементу UI, используйте конструкцию «@+id/yourvalue». Условно это создаст и назначит новый id «yourvalue» соответствующему элементу UI. Позже, в Java-коде Вы можете получить доступ к этим элементам UI с помощью метода findViewById(R.id.yourvalue).
Определение макетов через XML обычно предпочтительней, поскольку отделяет программной логику от определения макетов и позволяет легче определять разные ресурсы макетов, для разных устройств. Можно также смешивать оба подхода.
Источник
Get Started with Play Games Services for Android
Welcome to Android game development with the Google Play games services!
The Play Games SDK provides cross-platform Google Play games services that lets you easily integrate popular gaming features such as achievements, leaderboards, and Saved Games in your tablet and mobile games.
This training will guide you to install a sample game application for Android and quickly get started to create your own Android game. The Type-a-Number Challenge sample app demonstrates how you can integrate achievements and leaderboards into your game.
Before you begin
To prepare your app, complete the steps in the following sections.
App prerequisites
Make sure that your app’s build file uses the following values:
- A minSdkVersion of 19 of higher
- A compileSdkVersion of 28 or higher
Set up your game in Google Play Console
The Google Play Console is where you manage Google Play games services for your game, and configure metadata for authorizing and authenticating your game. For more information, see Setting Up Google Play Games Services.
Configure your app
In your project-level build.gradle file, include Google’s Maven repository and Maven central repository in both your buildscript and allprojects sections:
Add the Google Play services dependency for the Play Games SDK to your module’s Gradle build file, which is commonly app/build.gradle :
Sample App Guide
This training will guide you to install a sample game app for Android and quickly get started to create your own Android game. The Type-a-Number Challenge sample app demonstrates how you can integrate achievements and leaderboards into your game.
Step 1: Download the sample app
For this developer guide, you will need to download the Type-a-Number Challenge sample Android application.
To download and set up the sample application in Android Studio:
- Download the Android samples from the samples download page.
- Import the android-basic-samples project. This project includes TypeANumber and other Android game samples. To do this in Android Studio:
- Click File >Import Project.
- Browse to the directory where you downloaded android-basic-samples on your development machine. Select the file android-basic-samples/build.gradle and click OK.
- In the TypeANumber module, open AndroidManifest.xml and change the package name from com.google.example.games.tanc to a different package name of your own. The new package name must not start with com.google , com.example , or com.android .
Step 2: Set up the game in the Google Play Console
The Google Play Console is where you manage Google Play games services for your game, and configure metadata for authorizing and authenticating your game.
To set up the sample game in the Google Play Console:
- Point your web browser to the Google Play Console, and sign in. If you haven’t registered for the Google Play Console before, you will be prompted to do so.
- Follow these instructions to add your game to the Google Play Console.
- When asked if you use Google APIs in your app, select I don’t use any Google APIs in my game yet.
- For the purpose of this developer guide, you can fill up the form with your own game details. For convenience, you can use the placeholder icons and screenshots provided in the Downloads page.
- Follow these instructions to generate an OAuth 2.0 client ID for your Android app.
- When linking your Android app, make sure to specify the exact package name you used previously when renaming the sample package.
- You can use the Generate Signed APK Wizard in Android Studio to generate a new keystore and signed certificate if you don’t have one already. To learn how to run the Generate Signed APK Wizard, see Signing Your App in Android Studio.
- Make sure to record the following information for later:
- Your application ID: This is a string consisting only of digits (typically 12 or more), at the beginning of your client ID.
- Your signing certificate: Note which certificate you used when setting up your API access (the certificate whose SHA1 fingerprint you provided). You should use the same certificate to sign your app when testing or releasing your app.
- Configure achievements for Type-a-Number Challenge:
- Select the Achievements tab in the Google Play Console.
- Add the following sample achievements:
Name Description Special Instructions Prime Get a score that’s a prime number. None Humble Request a score of 0. None Don’t get cocky, kid Request a score of 9999 in either mode. None OMG U R TEH UBER LEET! Receive a score of 1337. Make this a hidden achievement. Bored Play the game 10 times. Make this an an incremental achievement with 10 steps to unlock. Really Really Bored Play the game 100 times. Make this an an incremental achievement with 100 steps to unlock. - Record the IDs (long alphanumeric strings) for each achievement that you created.
- Configure achievements that are appropriate for your game. To learn more, see the concepts behind achievements and how to implement achievements in Android.
- Configure the leaderboards for Type-a-Number Challenge:
- Select the Leaderboards tab in the Google Play Console.
- Add two sample leaderboards: one named “Easy High Scores” and another named “Hard High Scores”. Both leaderboards should use Integer score formatting with 0 decimal places, and an ordering type of Larger is better.
- Record the IDs (long alphanumeric strings) for each leaderboard you created.
- Configure leaderboards that are appropriate for your game. To learn more, see the concepts behind leaderboards and how to implement leaderboards in Android.
- Add test accounts for your game. This step is needed only for apps that have not yet been published in the Google Play Console. Before the app is published, only the test accounts listed in the Google Play Console can log in. However, once an application is published, everyone is allowed to log in.
Warning: If you try to make Play Games SDK calls for an unpublished game by using an account that’s not listed as a test account, the Google Play games services will behave as if the game did not exist and you’ll get back the ConnectionResult.SIGN_IN_REQUIRED return code. If you attempt to launch ConnectionResult.startResolutionForResult() , you’ll get back GamesActivityResultCodes.RESULT_SIGN_IN_FAILED .
Step 3: Modify your code
To run the game, you need to configure the application ID as a resource in your Android project. You will also need to add games metadata in the AndroidManifest.xml .
- Open res/values/ids.xml and replace the placeholder IDs. If you are creating an Android game from scratch, you will need to create this file first.
- Specify your application ID in the app_id resource.
- Specify each achievement ID that you created earlier in the corresponding achievement_* resource.
- Specify each leaderboard ID that you created earlier in the corresponding leaderboard_* resource.
- Open AndroidManifest.xml and enter your package name in the package attribute of the manifest > element. If you are creating an Android game from scratch, make sure that you also add the following code inside the application > element:
Step 4: Test your game
To ensure that Google Play games services are functioning correctly in your game, test the application before you publish it on Google Play.
To run your game on your physical test device:
- Verify that you have set up the test account that you are using to log in to the app (as described in Step 2).
- Export an APK and sign it with the same certificate that you used to set up the project in Google Play Console. To export a signed APK in Android Studio, click Build >Generate Signed APK.
- Install the signed APK on your physical test device by using the adb tool. To learn how to install an application, see Running on a Device.
Warning: When you run the application directly from Android Studio, Android Studio will sign the application with your debug certificate by default. If you did not use this debug certificate when setting up the application in Google Play Console, this will cause errors. Make sure to run an APK that you exported and signed with a certificate that matches one of the certificates you used during the application setup in Google Play Console.
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.
Источник