Android studio: качественные приложения для разных устройств android

Объединяем Activity и View

Вы можете использовать java-файлы, размещенные в app / src / main / java чтобы установить логические связи в приложении.

Откройте MainActivity.java и добавьте эти данные под уже существующие:

import java.util.Random;import android.view.View;import android.widget.Button;import android.widget.ImageView;import android.widget.TextView; import com.daimajia.androidanimations.library.Techniques;import com.daimajia.androidanimations.library.YoYo;

Первые пять импортов указывают на соответствующие классы в вашем коде: Random, View, Button, ImageView и TextView. Следующие два импорта указывают на то, что вы будете использовать два класса из библиотек, в т.ч. build.gradle для анимаций. В MainActivity.java в класс MainActivity добавьте:

String fortuneList[] = {"Don’t count on it","Ask again later","You may rely on it","Without a doubt","Outlook not so good","It's decidedly so","Signs point to yes","Yes definitely","Yes","My sources say NO"}; TextView mFortuneText;Button mGenerateFortuneButton;ImageView mFortuneBallImage;

В этом небольшом отрезке кода вы установили 4 переменных для активности. Первая — строки, которые определяют возможные состояния, другие три — элементы UI, которые вы создали в макете/разметке.

Теперь замените содержимое метода onCreate() следующими данными:

// 1:super.onCreate(savedInstanceState);// 2:setContentView(R.layout.activity_main);Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);setSupportActionBar(toolbar);// 3:mFortuneText = (TextView) findViewById(R.id.fortuneText);mFortuneBallImage = (ImageView) findViewById(R.id.fortunateImage);mGenerateFortuneButton = (Button) findViewById(R.id.fortuneButton); // 4:mGenerateFortuneButton.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {// 5:int index = new Random().nextInt(fortuneList.length);mFortuneText.setText(fortuneList);// 6:YoYo.with(Techniques.Swing).duration(500).playOn(mFortuneBallImage);}});
  • Проверьте, что активность готова (реализация суперкласса).
  • Укажите, что макет для данной активности представлен макетом, который вы создали ранее, проверьте панель инструментов.
  • Заполните значения трех переменных, которые вы создали прежде в компонентах views макета с помощью метода findViewById. Значение id то же, что и в макете XML.
  • Добавьте OnClickListener на кнопке. Это простой класс, который инкапсулирует (упаковывает) функциональность, которую, в свою очередь, вызывает нажатие кнопки.
  • Выберите произвольный вариант из набора fortuneList для данного приложения, и обновите текст fortune text, чтобы это показать.
  • Используйте библиотеку сторонних разработчиков, чтобы добавить зависимость в файл gradle, и таким образом добавить анимацию в приложение.

Уже почти готово. Но нужно убрать плавающую кнопку. Перейдите в res / layout и откройте activity_main.xml.

В этом файле макета содержится ссылка на content_main.xml, который вы прежде редактировали. Он по умолчанию определяет контент (тулбар и плавающая кнопка действия). Однако в данном конкретном приложении (Fortune Ball) плавающая кнопка не нужна. Поэтому уберите следующий блок кода из xml-файла:

Теперь в правом нижнем углу нет плавающей кнопки.

Задайте вопрос (What’s my fortune?) — нажмите кнопку. Проверьте работу приложения.

Choose resources to make public

All resources in a library default to public. To make all resources
implicitly private, you must define at least one specific attribute as public.
Resources include all files in your project’s directory, such
as images. To prevent users of your library from accessing resources intended
only for internal use, you should use this automatic private designation
mechanism by declaring one or more public resources. Alternately, you can make
all resources private by adding an empty tag , which
marks nothing as public, which makes everything else (all resources) private.

To declare a public resource, add a declaration to your library’s
file. If you haven’t added public resources before, you need to create the
file in the directory of your library.

The following example code creates two public string resources with the names
and :

You should make public any resources that you want to remain visible to
developers using your library.

Implicitly making attributes private not only prevents users of your library
from experiencing code completion suggestions from internal library resources
but also allows you to rename or remove private resources without breaking
clients of your library. Private resources are filtered out of code completion,
and Lint warns you when you try to
reference a private resource.

When building a library, the Android Gradle plugin gets the public resource definitions and extracts
them into the file, which is then packaged inside the AAR file.

Настройки на экране приветствия (Welcome Screen)

На экране приветствия появилась возможность кастомизации некоторых настроек. Первая настройка касается упорядочения проектов. Если их слишком много и вы хотите часть из них сгруппировать, то такая возможность появилась в Android Studio 2.0. Допустим, вы хотите объединить проекты, связанные с котами в отдельную группу Cats. Щёлкаем правой кнопкой мыши на проектах и выбираем пункт New Project Group.

В следующем окне выбираем название.

У вас появится новая группа. Теперь достаточно выбрать нужные вам проекты и через контекстное меню выбрать пункт Move To Group, далее выбираем нужную группу.

Теперь у нас порядок, проекты с котиками хранятся в одном месте.

Следующая кастомизациия касается значка проекта. По умолчанию, на экране приветствия вы не видите никаких значков у проектов. Снова вызываем контекстное меню и выбираем пункт Change Icon.

В следующем окне вы увидите стандартные значки студии для проекта. Нажимаем на ссылку Change… и выбираем свой значок для проекта. Можно выбрать значки для стандартной и тёмной темы студии.

Теперь вам будет проще найти свой проект по значку.

Create a library module

To create a new library module in your project, proceed as follows:

  1. Click File > New > New Module.
  2. In the Create New Module window that appears,
    click Android Library, then click Next.

    There’s also an option to create a Java Library, which
    builds a traditional JAR file. While a JAR file is useful for many projects—
    especially when you want to share code with other platforms—it does not
    allow you to include Android resources or manifest files, which is very useful
    for code reuse in Android projects. So this guide focuses on creating Android
    libraries.

  3. Give your library a name and select a minimum SDK version for the code
    in the library, then click Finish.

Once the Gradle project sync completes, the library module appears in
the Project panel on the left. If you don’t see the new module
folder, make sure it’s displaying the .

Convert an app module to a library module

If you have an existing app module with all the code you want to reuse,
you can turn it into a library module as follows:

  1. Open the module-level file.
  2. Delete the line for the .
    Only an Android app module can define this.
  3. At the top of the file, you should see the following:
    apply plugin: 'com.android.application'
    

    Change it to the following:

    apply plugin: 'com.android.library'
    
  4. Save the file and click File > Sync Project with Gradle Files.

That’s it. The entire structure of the module remains the same, but it now
operates as an Android library and the build will now create an AAR file
instead of an APK.

When you want to build the AAR file, select the library module in the
Project window and then click Build > Build APK.

Несколько локалей

В Android 7.0 (API 24) пользователь может установить несколько локалей. В этом случае, если не будут найдены ресурсы для первой локали, то будут искаться ресурсы для второй локали. Таким образом, если француз знает два языка, например, французский и испанский, а в приложение не поддерживает французского, но поддерживает испанский, то пользователь увидит текст на испанском, а не на английском.

Но тут есть одна особенность, если вы в своём приложении используете библиотеку совместимости appcompat-v7. Она может показать текст на английском, если не найдет ресурсов для первой локали, игнорируя ресурсы второй локали. Чтобы избежать проблемы, добавьте в build.gradle модуля дополнительную настройку.

Monitor the build process

You can view details about the build process by clicking View > Tool
Windows > Build
(or by clicking Build
in the tool window bar). The window displays the tasks that
Gradle executes in order to build your app, as shown in figure 3.

  1. Build tab: Displays the tasks Gradle executes as a tree,
    where each node represents either a build phase or a group
    of task dependencies. If you receive build-time or compile-time errors,
    inspect the tree and select an element to read the error output, as shown in
    figure 4.

  2. Sync tab: Displays tasks that Gradle executes to sync with your
    project files. Similar to the Build tab, if you encounter a sync
    error, select elements in the tree to find more information about the error.
  3. Restart: Performs the same action as selecting Build >
    Make Project
    by generating intermediate build files for all modules in
    your project.
  4. Toggle view: Toggles between displaying task execution
    as a graphical tree and displaying more detailed text output from Gradle—this
    is the same output you see in the Gradle Console

    window on Android Studio 3.0 and earlier.

If your build variants use product flavors, Gradle also invokes tasks to
build those product flavors. To view the list of all available build tasks,
click View > Tool Windows > Gradle (or click Gradle
in the tool window bar).

If an error occurs during the build process, Gradle may recommend some command-line
options to help you resolve the issue, such as or
. To use command-line options with your build process:

  1. Open the Settings or Preferences
    dialog:

    • On Windows or Linux, select File >
      Settings from the menu bar.
    • On Mac OSX, select Android Studio >
      Preferences from the menu bar.
  2. Navigate to Build, Execution, Deployment >
    Compiler.
  3. In the text field next to Command-line Options, enter your
    command-line options.
  4. Click OK to save and exit.

Gradle applies these command-line options the next time you try building
your app.

Обзор AndroidManifest.xml

У каждого приложения под Android есть файл AndroidManifest.xml, который находится в папке manifests. Этот XML-файл сообщает вашей системе о требованиях приложения. Присутствие этого файла обязательно, т. к. именно он позволяет системе Android создать приложение.

Откройте папку manifests и AndroidManifest.xml. Двойной клик откроет файл.

Теги manifest и application нужны для manifest, появляются только один раз.

Каждый тег также определяет набор атрибутов, наряду с названием элемента. К примеру, некоторые атрибуты в application могут быть такими:

android:icon, android:label и android:theme

Среди прочего в manifest может появиться:

  • uses-permission: запрашивает специальное разрешение, которое выдается приложению для корректной работы. К примеру, приложение должно запрашивать разрешение у пользователя, чтобы получить доступ к сети — в случае, если вы добавите разрешение android.permission.INTERNET.
  • activity: сообщает об активности, которая частично отвечает за визуальный UI и логику. Любая активность, которая предусмотрена в приложении, должна добавляться в manifest — неотмеченную активность система не заметит, и она не будет отображаться в приложении.
  • service: добавляет сервис, который вы собираетесь использовать, чтобы реализовать продолжительные операции или расширенные коммуникации API с другими приложениями. Примером в данном случае может служить сетевой вызов, с помощью которого приложение получает данные. В отличие от активностей, у сервисов нет пользовательских интерфейсов.
  • receiver: благодаря приемнику широковещательных сообщений приложение получает сигналы о системных сообщениях или сообщениях других приложений, даже когда другие компоненты приложения не запущены. Пример такой ситуации — батарея с низким уровнем заряда и уведомление об этом операционной системы.

Полный список тегов можно найти в manifest-файле на сайте Android Developer.

Linux

To install Android Studio on Linux, proceed as follows:

  1. Unpack the file you downloaded to an
    appropriate location for your applications, such as within
    for your user profile, or
    for shared users.

    If you’re using a 64-bit version of Linux, make sure you first install the
    .

  2. To launch Android Studio, open a terminal,
    navigate to the directory,
    and execute .
  3. Select whether you want to import previous Android Studio settings
    or not, then click OK.
  4. The Android Studio Setup Wizard guides you through the rest of the
    setup, which includes downloading Android SDK components
    that are required for development.

Tip:
To make Android Studio available in your list of applications, select
Tools > Create Desktop Entry from the Android Studio menu bar.

Required libraries for 64-bit machines

If you are running a 64-bit version of Ubuntu, you need to install some 32-bit
libraries with the following command:

sudo apt-get install libc6:i386 libncurses5:i386 libstdc++6:i386 lib32z1 libbz2-1.0:i386

If you are running 64-bit Fedora, the command is:

sudo yum install zlib.i686 ncurses-libs.i686 bzip2-libs.i686

That’s it.
The following video shows each step of the recommended setup procedure.

As new tools and other APIs become available, Android Studio tells you
with a pop-up, or you can check for updates by clicking Help >
Check for Update.

Debug and profile tools

Android Studio assists you in debugging and improving the performance of your
code, including inline debugging and performance analysis tools.

Inline debugging

Use inline debugging to enhance your code walk-throughs in the debugger view
with inline verification of references, expressions, and variable values.
Inline debug information includes:

  • Inline variable values
  • Referring objects that reference a selected object
  • Method return values
  • Lambda and operator expressions
  • Tooltip values

To enable inline debugging, in the Debug window, click Settings
and select the checkbox for Show Values Inline.

Performance profilers

Android Studio provides performance profilers so you can more easily track your
app’s memory and CPU usage, find deallocated objects, locate memory leaks,
optimize graphics performance, and analyze network requests. With your app
running on a device or emulator, open the Android Profiler tab.

For more information about performance profilers, see
Performance profiling tools.

Heap dump

When you’re profiling memory usage in Android Studio, you can simultaneously
initiate garbage collection and dump the Java heap to a heap snapshot in an
Android-specific HPROF binary format file. The HPROF viewer displays classes,
instances of each class, and a reference tree to help you track memory usage
and find memory leaks.

For more informatin about working with heap dumps, see
Inspect the heap and allocations.

Memory Profiler

You can use Memory Profiler to track memory allocation and watch where objects
are being allocated when you perform certain actions. Knowing these allocations
enables you to optimize your app’s performance and memory use by adjusting the
method calls related to those actions.

For information about tracking and analyzing allocations, see
Inspect the heap and allocations.

Data file access

The Android SDK tools, such as Systrace,
and logcat,
generate performance and debugging data for detailed app analysis.

To view the available generated data files, open the Captures tool window. In
the list of the generated files, double-click a file to view the data.
Right-click any files to convert them to the standard
Investigate your RAM usage file format.

Code inspections

Whenever you compile your program, Android Studio automatically runs configured
Lint and other

IDE inspections to help you easily
identify and correct problems with the structural quality of your code.

The Lint tool checks your Android project source files for potential bugs and
optimization improvements for correctness, security, performance, usability,
accessibility, and internationalization.

In addition to Lint checks, Android Studio also performs IntelliJ code
inspections and validates annotations to streamline your coding workflow.

For more information, see
Improve your code with lint checks.

Annotations in Android Studio

Android Studio supports annotations for variables, parameters, and return
values to help you catch bugs, such as null pointer exceptions and resource
type conflicts. The Android SDK Manager packages the Support-Annotations
library in the Android Support Repository for use with Android Studio. Android
Studio validates the configured annotations during code inspection.

For more details about Android annotations, see
Improve code inspection with annotations.

Log messages

When you build and run your app with Android Studio, you can view
adb output and device log messages
in the Logcat window.

Performance profiling

If you want to profile your app’s CPU, memory, and network performance,
open the Android Profiler,
by clicking View > Tool Windows > Android Profiler.

Configure the IDE for low-memory machines

If you are running Android Studio on a machine with less than the recommended
specifications (see ),
you can customize the IDE to improve performance on your machine, as follows:

  • Reduce the maximum heap size available to Android Studio: Reduce the
    maximum heap size for Android Studio to 512Mb. For more information on changing
    maximum heap size, see .
  • Update Gradle and the Android plugin for Gradle: Update to the latest
    versions of Gradle and the Android plugin for Gradle to ensure you are taking
    advantage of the latest improvements for performance. For more information
    about updating Gradle and the Android plugin for Gradle, see the
    Android plugin for Gradle Release Notes.
  • Enable Power Save Mode: Enabling Power Save Mode turns off a number of
    memory- and battery-intensive background operations, including error
    highlighting and on-the-fly inspections, autopopup code completion, and
    automatic incremental background compilation. To turn on Power Save Mode,
    click File > Power Save Mode.
  • Disable unnecessary lint checks: To change which lint checks Android
    Studio runs on your code, do the following:

    1. Click File > Settings (on macOS, Android Studio > Preferences)
      to open the Settings dialog.
    2. In the left pane, expand the Editor section and click
      Inspections.
    3. Click the checkboxes to select or deselect lint checks as appropriate for
      your project.
    4. Click Apply or OK to save your changes.
  • Debug on a physical device: Debugging on an emulator uses more memory than
    debugging on a physical device, so you can improve overall performance for
    Android Studio by debugging on a physical device.

  • Include only necessary Google Play services as dependencies: Including
    Google Play Services as dependencies in your project increases the amount of
    memory necessary. Only include necessary dependencies to improve memory usage
    and performance. For more information, see
    .

  • Turn on Offline Mode for Gradle: If you have limited bandwitch, turn on
    Offline Mode to prevent Gradle from attempting to download missing dependencies
    during your build. When Offline Mode is on, Gradle will issue a build failure if
    you are missing any dependencies, instead of attempting to download them. To
    turn on Offline Mode, do the following:

    1. Click File > Settings (on macOS, Android Studio > Preferences) to
      open the Settings dialog.
    2. In the left pane, expand Build, Execution, Deployment and then click
      Gradle.
    3. Under Global Gradle settings, check the Offline work checkbox.
    4. Click Apply or OK for your changes to take effect.
  • Reduce the maximum heap size available for Gradle: Gradle’s default
    maximium heap size is 1,536 MB. Reduce the value by overriding the
    property in the file, as shown below:

  • Do not enable parallel compilation: Android Studio can compile independent
    modules in parallel, but if you have a low-memory system you should not turn on
    this feature. To check this setting, do the following:

    1. Click File > Settings (on macOS, Android Studio > Preferences) to
      open the Settings dialog.
    2. In the left pane, expand Build, Execution, Deployment and then click
      Compiler.
    3. Ensure that the Compile independent modules in parallel option is
      unchecked.
    4. If you have made a change, click Apply or OK for your change to
      take effect.

Build and deploy an APK

Although is the best way to
package your app and upload it to the Play Console, building an APK is better
suited for when you want quickly test a debug build or share your app
as a deployable artifact with others.

Build a debug APK

For immediate app testing and debugging, you can build a debug APK.
The debug APK is signed with a debug key provided by the SDK tools and
allows debugging through .

To build a debug APK, open a command line and navigate to the root of your
project directory. To initiate a debug build, invoke the
task:

gradlew assembleDebug

This creates an APK named in
.
The file is already signed with the debug key and aligned with
, so you can
immediately install it on a device.

Or to build the APK and immediately install it on a running emulator or
connected device, instead invoke :

gradlew installDebug

The «Debug» part in the above task names is just a
camel-case version of the build variant name, so it can be replaced with whichever build type or
variant you want to assemble or install. For example, if you have a «demo»
product flavor, then you can build the debug version with the
task.

To see all the build and install tasks available for each variant (including
uninstall tasks), run the task.

Also see the section about how to and .

Build a release APK

When you’re ready to release and distribute your app, you must build a
release APK that is signed with your private key. For more information, go to
section about how to .

Deploy your app to the emulator

To use the Android Emulator, you must using Android Studio.

Once you have an AVD, start the Android Emulator and install your
app as follows:

  1. In a command line, navigate to
    and start the emulator by
    specifying your AVD:

    emulator -avd avd_name

    If you’re unsure of the AVD name, execute
    .

  2. Now you can install your app using either one of the Gradle install tasks
    mentioned in the section about how to
    or the
    tool.

    If the APK is built using a developer preview SDK (if the is
    a letter instead of a number), you must include the

    with the command to install a test APK.

    adb install path/to/your_app.apk
    

    All APKs you build are saved in
    .

For more information, see Run Apps on the Android Emulator.

Deploy your app to a physical device

Before you can run your app on a device, you must enable USB
debugging on your device. You can find the option under
Settings > Developer options.

Note: On Android 4.2 and newer,
Developer options is hidden by default. To make it available,
go to Settings > About phone and tap Build
number seven times. Return to the previous screen to find
Developer options.

Once your device is set up and connected via USB, you can install your app
using either the Gradle install tasks mentioned
in the section about how to or the
tool:

adb -d install path/to/your_app.apk

All APKs you build are saved in
.

For more information, see
Run Apps on a Hardware Device.

Testing your application for release

Testing the release version of your application helps ensure that your application runs properly
under realistic device and network conditions. Ideally, you should test your application on at least
one handset-sized device and one tablet-sized device to verify that your user interface elements are
sized correctly and that your application’s performance and battery efficiency are acceptable.

As a starting point for testing, see
What to Test. This article provides
a summary of common Android situations that you should consider when you are testing. When you are
done testing and you are satisfied that the release version of your application
behaves correctly, you can release your application to users. For more information, see
. If you are publishing your application on Google Play, see
Launch Checklist
for Google Play.

Set proxy settings

Proxies serve as intermediary connection points between HTTP clients and web
servers that add security and privacy to internet connections.

To support running Android Studio behind a firewall, set the proxy settings for
the Android Studio IDE. Use the Android Studio IDE HTTP Proxy settings page to
set the HTTP proxy settings for Android Studio.

When running the Android plugin for Gradle from the command line or on machines
where Android Studio is not installed, such as continuous integration servers,
set the proxy settings in the Gradle build file.

Set up the Android Studio proxy

Android Studio supports HTTP proxy settings so you can run Android Studio behind
a firewall or secure network. To set the HTTP proxy settings in Android Studio:

  1. From the menu bar, click File > Settings (on macOS, click
    Android Studio > Preferences).
  2. In the left pane, click Appearance & Behavior > System Settings > HTTP
    Proxy. The HTTP Proxy page appears.
  3. Select Auto-detect proxy settings to use an automatic proxy configuration
    URL for the proxy settings or Manual proxy configuration to enter each of
    the settings yourself. For a detailed explanation of these settings, see HTTP Proxy.
  4. Click Apply or OK for your changes to take effect.

Android plugin for Gradle HTTP proxy settings

When running the Android plugin from the command line or on machines where
Android Studio is not installed, set the Android plugin for Gradle proxy
settings in the Gradle build file.

For application-specific HTTP proxy settings, set the proxy settings in the
file as required for each application module.

For project-wide HTTP proxy settings, set the proxy settings in the
file.

For information about using Gradle properties for proxy settings, see the
Gradle User Guide.

Attach Kotlin/Java sources

By default, Android Studio extracts Kotlin/Java code from your APK and saves
it as files. To debug the Kotlin/Java code using breakpoints, you
need to point the IDE to the or source files that correspond to
the files you want to debug.

To attach Kotlin/Java sources, proceed as follows:

  1. Double click on a file from the Project pane (use the
    Android view). After opening the file, the editor displays a
    banner asking you to select the Kotlin/Java sources:
  1. Click Attach Kotlin/Java Sources from the banner at the top of the editor
    window.
  2. Navigate to the directory with the app’s Kotlin/Java source files and click
    Open.

In the Project window, the IDE replaces files with their
corresponding or files. The IDE also includes inner classes
automatically. You can now add breakpoints and
debug your app as you normally would.

Customize your VM options

The file allows you to customize options for Android Studio’s
JVM. To improve Studio’s performance, the most common option to adjust is the
maximum heap size, but you can also use the file to override
other default settings such as initial heap size, cache size, and Java garbage
collection switches.

To create a new file or to open your existing one, use the
following steps:

  1. Click Help > Edit Custom VM Options. If you have never edited VM
    options for Android Studio before, the IDE prompts you to create a new
    file. Click Yes to create the file.
  2. The file opens in the editor window of Android Studio.
    Edit the file to add your own customized VM options. For a full list of
    customizable JVM options, see Oracle’s Java HotSpot VM Options page.

The file you create gets added to the default
file, located in the directory inside your Android
Studio installation folder.

Note that you should never directly edit the file found
inside the Android Studio program folder. While you can access the file to
view Studio’s default VM options, editing only your own file
ensures that you don’t override important default settings for Android Studio.
Therefore, in your file, override only the attributes you
care about and allow Android Studio to continue using default values for any
attributes you have not changed.

Maximum heap size

By default, Android Studio has a maximum heap size of 1280MB. If you are working
on a large project, or your system has a lot of RAM, you can improve performance
by increasing the maximum heap size for Android Studio processes, such as the
core IDE, Gradle daemon, and Kotlin daemon.

Android Studio automatically checks for possible heap size optimizations and
notifies you if it detects that performance can be improved.

If you use a 64-bit system that has at least 5 GB of RAM, you can also adjust
the heap sizes for your project manually. To do so, follow these steps:

  1. Click File > Settings from the menu bar (or
    Android Studio > Preferences on macOS).
  2. Click Appearance & Behavior > System Settings > Memory Settings.

  3. Adjust the heap sizes to match your desired amounts.

  4. Click Apply.

    If you changed the heap size for the IDE, you must restart Android Studio
    before the new memory settings are applied.

Ссылка на основную публикацию