Android tutorial android developers

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-устройстве. Значения со знаком @ ссылаются на файлы ресурсов, которые содержат актуальные значения. Это упрощает работу с разными ресурсами, такими как строки, цвета, иконки, для разных устройств и упрощает перевод приложений.

Читайте также:  Metal gear rising revengeance для андроид

Часть «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 обычно предпочтительней, поскольку отделяет программной логику от определения макетов и позволяет легче определять разные ресурсы макетов, для разных устройств. Можно также смешивать оба подхода.

Источник

Developer guide

Android’s enterprise features provide organizations with a secure, flexible, and unified Android mobility platform—combining devices, applications, and management. Android apps are compatible with Android’s enterprise features by default. However, there are additional features you can use to make your app work best on managed Android devices:

  • Work profile compatibility—Modify your Android app so it functions best on a managed device.
  • Managed configurations—Modify your app to allow IT admins the option to specify custom settings for your apps.
  • Dedicated devices—Optimize your app so that it can be deployed on an Android device as a kiosk.
  • Single Sign-On (SSO)—Simplify the sign-on process for users signing in to different apps on their managed Android device.

Prerequisites

  1. You’ve created an Android app.
  2. You’re ready to modify your app so that it works best for organizations.
  3. Minimum version: Android 5.0 Lollipop recommended version: Android 6.0 Marshmallow and later.

Note: Android’s enterprise features are built into most Android 5.0 devices; however, Android 6.0 and later offers additional features, especially with regard to dedicated devices.

Work profiles

You can manage a user’s business data and applications through a work profile. A work profile is a managed corporate profile associated with the primary user account on an Android device. A work profile securely isolates work apps and data from personal apps and data. This work profile is in a separate container from the personal profile, which your user controls. These separate profiles allow organizations to manage the business data they care about, but leave everything else on a user’s device under the user’s control. For a deep dive into best practices, see the Work profiles guide. For an overview of those best practices, see below.

Key features of a work profile

  • Separate and secure profile
  • Managed Google Play for application distribution
  • Separate badged work applications
  • Profile-only management capabilities controlled by an admin

Work profile benefits on Android 5.0+

  • Full device encryption
  • One Android application package (APK) for both profiles when there’s a personal profile and a work profile present on the device
  • Device policy controller (DPC) is limited to the work profile
  • Device administration via the DevicePolicyManager class

Considerations for work profiles

  • The Android system prevents intents from crossing profiles and IT admins can enable or disable system apps.
  • A file path (Uniform Resource Identifier [URI]) that’s valid on one profile may not be valid on the other.
Читайте также:  Cheapshot андроид последняя версия

Prevent intents from failing between profiles

It’s difficult to know which intents can cross between profiles, and which ones are blocked. The only way to know for sure is by testing. Before your app starts an activity, you should verify that the request is resolved by calling Intent.resolveActivity() .

  • If it returns null , the request doesn’t resolve.
  • If it returns something, it shows that the intent resolves, and it’s safe to send the intent.

Note: For detailed testing instructions, see Prevent Failed Intents.

Share files across profiles

Some developers use URIs to mark file paths in Android. However, because there are separate file systems when a work profile is present, we recommend:

Use:
Content URIs
  • The content URIs contain the authority, path, and ID for a specific file. You can generate this using FileProvider subclass. Learn more
  • Share and grant permissions to access the content URI using an Intent. Permissions can only be passed across the profile boundary using Intents. If you grant another app access rights to your file using Context.grantUriPermission() , it only is granted for that app in the same profile.
Don’t use:
File URI
  • Contains the absolute path of the file on the device’s storage.
  • A file path URI that’s valid on one profile isn’t valid on the other.
  • If you attach a file URI to an intent, a handler is unable to access the file in another profile.

Next steps: Once your app supports managed profiles, test it in a work profile. See Test your app.

Implement managed configurations

Managed configurations are a set of instructions that IT admins can use to manage their users’ mobile devices in a specific way. These instructions are universal and work across any EMM, allowing admins to remotely configure applications on their users’ phones.

If you’re developing apps for business or government, you may need to satisfy your industry’s specific set of requirements. Using managed configurations, the IT admin can remotely specify settings and enforce policies for their users’ Android apps; for example:

  • Configure if an app can sync data via cellular/3G, or only Wi-Fi
  • Allow or block URLs on a web browser
  • Configure an app’s email settings
  • Enable or disable printing
  • Manage bookmarks

Best practices for implementing managed configurations

The Set up Managed Configurations guide is the key source for information on how to build and deploy managed configurations. After you’ve reviewed this documentation, see recommendations below for additional guidance.

When first launching the app

As soon as you launch an application, you can see if managed configurations are already set for this app in onStart() or onResume() . Additionally, you can find out if your application is managed or unmanaged. For example, if getApplicationRestrictions() returns:

  • A set of application-specific restrictions—You can configure the managed configurations silently (without requiring user input).
  • An empty bundle—Your application acts like it’s unmanaged (for example, how the app behaves in a personal profile).
  • A bundle with a single key value pair with KEY_RESTRICTIONS_PENDING set to true—your application is being managed, but the DPC isn’t configured correctly. You should block this user from your app, and direct them to their IT admin.

Listen for changes to managed configurations

IT admins can change managed configurations and what policies they want to enforce on their users at any time. Because of this, we recommend you ensure that your app can accept new restrictions for your managed configuration as follows:

  • Fetch restrictions on launch—Your app should call getApplicationRestrictions() in onStart() and onResume() , and compare against old restrictions to see if changes are required.
  • Listen while running—Dynamically register ACTION_APPLICATION_RESTRICTIONS_CHANGED in your running activities or services, after you’ve checked for new restrictions. This intent is sent only to listeners that are dynamically registered, and not to listeners declared in the app manifest.
  • Unregister while not running—In onPause() , you should unregister for the broadcast of ACTION_APPLICATION_RESTRICTIONS_CHANGED .

Dedicated devices

Dedicated devices are kiosk devices used for a single purpose, such as digital signage displays, ticket printing kiosks, or checkout registers.

When an Android device is configured as a dedicated device, the user sees an application locked to the screen with no Home or Recent Apps buttons to escape the app. Dedicated devices can also be configured to show a set of applications, such as a library kiosk with an app for the library catalog and a web browser.

Set up single sign-on with Chrome custom tabs

Enterprise users often have multiple apps on their device, and they prefer to sign in once to access all of their work applications. Typically, users sign in through a WebView; however, there are a couple reasons why this isn’t ideal:

  1. Users often need to sign in multiple times with the same credentials. The WebView solution often isn’t a true Single Sign-On (SSO) experience.
  2. There can be security risks, including malicious applications inspecting cookies or injecting JavaScript® to access a user’s credentials. Even trusted developers are at risk if they rely on potentially malicious third-party SDKs.
Читайте также:  Наушники apple earpods работают с андроид или нет

A solution to both problems is to authenticate users using browser Custom Tabs, instead of WebView. This ensures that authentication:

  • Occurs in a secure context (the system browser) where the host app cannot inspect contents.
  • Has a shared cookie state, ensuring the user has to sign in only once.

Requirements

Custom Tabs are supported back to API level 15 (Android 4.0.3). To use Custom Tabs you need a supported browser, such as Chrome. Chrome 45 and later implement this feature as Chrome Custom Tabs.

How do I implement SSO with custom tabs?

Google has open sourced an OAuth client library that uses Custom Tabs, contributing it to the OpenID Connect working group of the OpenID Foundation. To set up Custom Tabs for SSO with the AppAuth library, see the documentation and sample code on GitHub.

Test your app

After you’ve developed your app, you’ll want to test it—both in a work profile and on a fully managed device. See the instructions below.

Use Test DPC to test your Android app

We provide the Test DPC app to help Android developers test their apps in an enterprise environment. Using Test DPC, you can set EMM policies or managed configuration values on a device—as if an organization managed the device using an EMM. To install Test DPC on a device, choose one of the following methods:

  • Install Test DPC from GooglePlay.
  • Build from the source on GitHub.

For more information on how to configure Test DPC, see the instructions below and the Test DPC User Guide.

Provision a work profile

To test your app in a work profile, you need to first provision a work profile on device using the Test DPC app, as follows:

  1. Install Test DPC on the device.
  2. In the Android launcher, tap the Set up Test DPC app icon.
  3. Follow the onscreen instructions.
  4. Install your app on the device and test to see how it runs in the work profile.

Android creates a work profile and installs a copy of Test DPC in the work profile. You use this work-badged instance of Test DPC to set policies and managed configurations in the work profile. To learn more about setting up a work profile for development, read the developer’s guide Work profiles.

Provision a fully managed device

Organizations use fully managed devices because they can enforce a full range of management policies on the device. To provision a fully managed device, follow these steps:

  1. Install Test DPC on the device.
  2. Confirm that there are no other users or a work profile on the device.
  3. Confirm that there are no accounts on the device.
  4. Run the following Android Debug Bridge (adb) command in your terminal:
  5. Once you’ve completed provisioning the device owner, you can test your app on that device. You should specifically test how managed configurations and intents work on that device.

You can also use other provisioning methods—see the Test DPC User Guide. To learn how IT admins typically enroll and provision Android-powered devices, read Provision devices.

End-to-end testing

After you’ve finished testing your app in the environments above, you’ll likely want to test your app in an end-to-end production environment. This process includes the steps a customer needs to take to deploy your app in their organization, including:

  • App distribution through Play
  • Server-side managed configuration
  • Server-side profile policy control

You need to access an EMM console to complete the end-to-end testing. The easiest way to get one is to request a testing console from your EMM. Once you have access, complete these tasks:

  1. Create a test version of your application with a new ApplicationId.
  2. Claim a managed Google domain and bind it to your EMM. If you already have a testing domain that’s bound to an EMM, you may need to unbind it to test it with your preferred EMM. Please consult your EMM for the specific unbinding steps.
  3. Publish your application to the private channel for their managed Google domain.
  4. Use the EMM console and EMM application to:
    1. Set up work devices.
    2. Distribute your application.
    3. Set managed configuration.
    4. Set device policies.

This process will differ based on your EMM. Please consult your EMM’s documentation for further details. Congrats! You’ve completed these steps and verified that your app works well for enterprise users.

Content and code samples on this page are subject to the licenses described in the Content License. Java is a registered trademark of Oracle and/or its affiliates.

Источник

Оцените статью