본문 바로가기
User Guide

app 만들어서 실행시키기 Build and Run Your App (20)

by 각종 잡상식 지식 모음 2016. 6. 10.
반응형

app 만들어서 실행시키기
Build and Run Your App

기본적으로, Android Studio는 Emulator나 물리적 장치에 설치하기 위하여, 단지 몇 번의 클릭으로 신규 프로젝트를 셋업합니다.
Instant Run을 사용하면, 새로운 APK를 구축하지 않고도 실행되고 있는 app에 methods 및 기본 app 리소스에 대한 변경사항을 push 할 수 있어서, 코드 변경을 거의 즉시 볼 수 있습니다.
By default, Android Studio sets up new projects to deploy to the Emulator or a physical device with just a few clicks. With Instant Run, you can push changes to methods and existing app resources to a running app without building a new APK, so code changes are visible almost instantly.

app을 빌드해서 실행시키려면, Run 'app' 를 클릭하세요.
Android Studio가 Gradle로 app을 빌드하고, 설치 타겟(emulator 또는 연결된 장치)을 선택하도록 요구하며, 그런 다음 app을 그 곳에 설치합니다.
사용자는 run configuration을 변경함으로써, 기본적인 이 동작의 일부(설치 타겟 자동화 선택)를 자기 입맛대로 조정할 수 있습니다.
To build and run your app, click Run 'app' . Android Studio builds your app with Gradle, asks you to select a deployment target (an emulator or a connected device), and then deploys your app to it. You can customize some of this default behavior, such as selecting an automatic deployment target, by changing the run configuration.

If you want to use the Android Emulator to run your app, you need to have an Android Virtual Device (AVD) ready. If you haven't already created one, then after you click Run 'app', click Create New Emulator in theSelect Deployment Target dialog. Follow the Virtual Device Configuration wizard to define the type of device you want to emulate. For more information, see Create and edit virtual devices.

If you're using a physical Android device, you need to enable USB debugging on the device. For more information, see Using hardware devices.

Note: You can also deploy your app in debug mode by clicking Debug 'app' . Running your app in debug mode allows you to set breakpoints in your code, examine variables and evaluate expressions at run time, and run debugging tools. To learn more, read about Debugging with Android Studio.

Change the run configuration

The run configuration specifies the module to run, package to deploy, activity to start, target device, emulator settings, and Logcat options. The default run configuration launches the default project activity and uses the Device Chooser for target device selection. If the default settings don't suit your project or module, you can customize the run configuration, or even create a new one, at the project, default, and module levels. To edit a run configuration:

  1. Select Run > Edit Configurations.
  2. Expand the Android Application item and select an existing run configuration.
    • To create a new run configuration, click the '+' button in the top left corner of the dialog box and select Android Application.
  3. With a run configuration selected, adjust your desired settings. For example, in the General tab, you can specify the APK installation settings, launch options, and deployment target options.

Change the build variant

By default, Android Studio builds the debug version of your app, which is intended only for testing, when you click Run 'app'. You need to build the release version to prepare your app for public release.

To change the build variant Android Studio uses, go to Build > Select Build Variant and select a different one from the drop-down menu. By default, new projects are set up with a debug and release build variant.

Using product flavors, you can create additional build variants for different versions of your app, each having different features or device requirements. To find out more about build variants and product flavors, go to Configure your build.

Monitor the build process

Gradle Console 을 클릭함으로써 빌드 과정에 대한 상세사항을 볼 수 있습니다.
이 콘솔이 app을 빌드하기 위하여 Gradle이 집행하는, 각 태스크를 그림1과 같이 보여줍니다.
You can view details about the build process by clicking Gradle Console . The console displays each task that Gradle executes in order to build your app, as shown in figure 1.

Figure 1. The Gradle Console in Android Studio.

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 Gradle  on the right side of the IDE window.

If an error occurs during the build process, the Messages window appears to describe the issue. Gradle may recommend some command-line options to help you resolve the issue, such as --stacktrace or --debug. 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 main menu.
    • On Mac OSX, select Android Studio > Preferences from the main menu.
  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 will apply these command-line options the next time you try building your app.

Generate APKs

Run 'app'을 클릭하면, Android Studio는 debug APK를 생성해서 그것을 타겟 장치에 설치합니다.
하지만 공개 배포를 위한 app의 배포를 생성하기 전에, sign your app방법을 먼저 배워야 합니다.
그런 다음 복수의  debug or release build variants의 서명된 APK를 생성시킬 수 있습니다.
To locate the generated APK files을 찾으려면, 그림2와 같이 pop-up dialog에 있는 링크를 클릭하세요.
When you click Run 'app', Android Studio generates a debug APK and deploys it to your target device. Before you can generate a release version of your app for public distribution, however, you must first learn how to sign your app. You can then generate multiple signed APKs of your debug or release build variants. To locate the generated APK files, click the link in the pop-up dialog, as shown in figure 2.

Figure 2. Click the link to locate the generated APK files.

About Instant Run


Introduced in Android Studio 2.0, Instant Run is a behavior for the Run and Debug  commands that significantly reduces the time between updates to your app. Although your first build may take longer to complete, Instant Run pushes subsequent updates to your app without building a new APK, so changes are visible much more quickly.

Instant Run is supported only when you deploy the debug build variant, use Android Plugin for Gradle version 2.0.0 or higher, and set minSdkVersion to 15 or higher in your app's module-level build.gradle file. For the best performance, set minSdkVersion to 21 or higher.

After deploying an app, a small, yellow thunderbolt icon appears within theRun  button (or Debug  button), indicating that Instant Run is ready to push updates the next time you click the button. Instead of building a new APK, it pushes just those new changes and, in some cases, the app doesn't even need to restart but immediately shows the effect of those code changes.

Instant Run pushes updated code and resources to your connected device or emulator by performing a hot swapwarm swap, or cold swap. It automatically determines the type of swap to perform based on the type of change you made. The video above provides interesting detail about how this all works under the hood. For a quick summary of how Instant Run behaves when you push certain code changes to a target device, however, see the following table.

Code ChangeInstant Run Behavior
  • Change implementation code of an existing method

Supported with hot swap: This is the fastest type of swap and makes changes visible much more quickly. Your application keeps running and a stub method with the new implementation is used the next time the method is called.

Hot swaps do not re-initialize objects in your running app. You may need to restart the current activity, or restart the app, before you see certain updates. By default, Android Studio automatically restarts the current activity after performing a hot swap. If you do not want this behavior, you can disable automatic activity restarts.

  • Change or remove an existing resource
Supported with warm swap: This swap is still very fast, but Instant Run must restart the current activity when it pushes the changed resources to your app. Your app keeps running, but a small flicker may appear on the screen as the activity restarts—this is normal.
Structural code changes, such as:
  • Add, remove, or change:
    • an annotation
    • an instance field
    • a static field
    • a static method signature
    • an instance method signature
  • Change which parent class the current class inherits from
  • Change the list of implemented interfaces
  • Change a class's static initializer
  • Reorder layout elements that use dynamic resource IDs

Supported with cold swap (API level 21 or higher): This swap is a bit slower because, although a new APK is not required, Instant Run must restart the whole app when it pushes structural code changes.

For target devices running API level 20 or lower, Android Studio deploys a full APK.

  • Change the app manifest
  • Change resources referenced by the app manifest
  • Change an Android widget UI element (requires aClean and Rerun)

When making changes to the app's manifest or resources referenced by the manifest, Android Studio automatically deploys a new build in order to apply these changes. This is because certain information about the app, such as its name, app icon resources, and intent filters, are determined from the manifest when the APK is installed on the device.

If your build process automatically updates any part of the app manifest, such as automatically iterating versionCode or versionName, you will not be able to benefit from the full performance of Instant Run. When using Instant Run, you should disable automatic updates to any part in the app manifest in your debug build variants.

When updating an Android widget UI element, you need to perform a Clean and Rerunto see your changes. Alternatively, because performing clean builds may take longer while using Instant Run, you can temporarily disable Instant Run while making updates to your widget UI.

Note: If you need to restart your app after a crash, do not launch it from your target device. Restarting your app from your target device does not apply any of your code changes since the last cold swap or incremental build. To launch your app with all your recent changes, click Run  (orDebug ) from Android Studio.

Use Rerun

When pushing code changes that affect certain initializers, such as changes to an app's onCreate() method, you need to restart your app for the changes to take effect. To perform an incremental build and restart the app, click Rerun .

If you need to deploy a clean build, select Run > Clean and Rerun 'app'  from the main menu, or hold down the Shift key while clicking Rerun . This action stops the running app, performs a full clean build, and deploys the new APK to your target device.

Disable automatic activity restart

When performing a hot swap, your app keeps running but Android Studio automatically restarts the current activity. To disable this default setting:

  1. Open the Settings or Preferences dialog:
    • On Windows or Linux, select File > Settings from the main menu.
    • On Mac OSX, select Android Studio > Preferences from the main menu.
  2. Navigate to Build, Execution, Deployment > Instant Run.
  3. Uncheck the box next to Restart activity on code changes.

If automatic activity restart is disabled, you can manually restart the current activity from the menu bar by selecting Run > Restart Activity.

Configure and optimize your project for Instant Run

Android Studio enables Instant Run by default for projects built using Android Plugin for Gradle 2.0.0 and higher.

To update an existing project with the latest version of the plugin:

  1. Open the Settings or Preferences dialog.
  2. Navigate to Build, Execution, Deployment > Instant Run and click Update Project, as shown in figure 3.

    If the option to update the project does not appear, it’s already up-to-date with the latest Android Plugin for Gradle.

    Figure 3. Updating the Android Plugin for Gradle for an existing project.

You also need to change the build variant to a debug version of your app to start using Instant Run.

Improve build times by configuring DEX resources

When you deploy a clean build, Android Studio instruments your app to allow Instant Run to push code and resource updates. Although updating the running app happens much more quickly, the first build may take longer to complete. You can improve the build process by configuring a fewDexOptions settings:

maxProcessCount
Sets the maximum number of DEX processes that can be started concurrently. If the Gradle daemon is already running, you need to stop the process before initializing it with a new maximum process count. You can terminate the Gradle daemon by calling one of the following from theTerminal window:
  • On Windows, call gradlew --stop
  • On Linux/Mac OSX, call ./gradlew --stop
javaMaxHeapSize
Sets the maximum memory allocation pool size for the dex operation. When passing a value, you can append the letter 'k' to indicate kilobytes, 'm' to indicate megabytes, or 'g' to indicate gigabytes.

The following example sets maxProcessCount to 4 and javaMaxHeapSize to "2g" in the module-level build.gradle file:

android {
 
...
  dexOptions
{
    maxProcessCount
4 // this is the default value
    javaMaxHeapSize
"2g"
 
}
}

You should experiment with these settings by incrementing their values and observing the effect on your build times. You could experience a negative impact to performance if you allocate too many resources to the dexing process.

Enable dexing-in-process and incremental Java compilation

Android Plugin for Gradle version 2.1.0 and higher features additional build process improvements, including incremental Java compilation and dexing-in-process. Incremental Java compilation is enabled by default and reduces compilation time during development by only recompiling portions of the source that have changed or need to be recompiled.

Dexing-in-process performs dexing within the build process rather than in a separate, external VM process. This not only makes incremental builds much faster, but also significantly speeds up full builds. To enable this feature, you need to set the Gradle daemon's maximum heap size to at least 2048 MB. You can do this by including the following in your project's gradle.properties file:

org.gradle.jvmargs = -Xmx2048m

If you have defined a value for javaMaxHeapSize in your module-level build.gradle file, you need to set the daemon's max heap size to the value ofjavaMaxHeapSize + 1024 MB. For example, if you have set javaMaxHeapSize to "2g", you need to add the following to your project's gradle.propertiesfile:

org.gradle.jvmargs = -Xmx3072m

Exclude your project from Windows Defender

On Windows systems, Windows Defender may cause slowdowns while using Instant Run. If you are using Windows Defender, you should exclude your Android Studio project folder from Windows Defender malware scans.

Improve build times when using Crashlytics

If your version of the Fabric Gradle plugin is lower than 1.21.6, Crashlytics may cause slower build times. To improve build performance while developing your app, you can either update the plugin to the latest version or disable Crashlytics for your debug build variant.

Limitations of Instant Run

Instant Run is designed to speed up the build and deploy process in most situations. However, there are some aspects to using Instant Run that might affect its behavior and compatibility with your app. If you experience any other issues while using Instant Run, please file a bug.

Deploy to multiple devices

Instant Run uses different techniques to perform hot, warm, and cold swaps that are specific to the API level of the target device. For this reason, while deploying an app to multiple devices at once, Android Studio temporarily turns off Instant Run.

Multidex your app

If your project is configured for Legacy Multidex—that is, when build.gradle is configured with multiDexEnabled true and minSdkVersion 20 or lower—and you deploy to target devices running Android 4.4 (API level 20) or lower, Android Studio disables Instant Run.

If minSdkVersion is set to 21 or higher, Instant Run automatically configures your app for multidex. Because Instant Run only works with the debug version of your app, you may need to configure your app for multidex when deploying your release build variant.

Run instrumented tests and performance profilers

Instrumented tests load both the debug APK and a test APK into the same process on a test device, allowing control methods to override the normal lifecycle of the app and perform tests. While running or debugging instrumented tests, Android Studio does not inject the additional methods required for Instant Run and turns the feature off.

While profiling an app, you should disable Instant Run. There is a small performance impact when using Instant Run and a slightly larger impact when overriding methods with a hot swap. This performance impact could interfere with information provided by performance profiling tools. Additionally, the stub methods generated with each hot swap can complicate stack traces.

Use third-party plugins

Android Studio temporarily disables the Java Code Coverage Library (JaCoCo) and ProGuard while using Instant Run. Because Instant Run only works with debug builds, this does not affect your release build.

Certain third-party plugins that perform bytecode enhancement may cause issues with how Instant Run instruments your app. If you experience these issues, but want to continue using Instant Run, you should disable those plugins for your debug build variant. You can also help improve compatibility with third-party plugins by filing a bug.

Push changes to multi-process apps

Instant Run only instruments your app's main process in order to perform hot swaps and warm swaps. When pushing code changes to other app processes, such as changes to a method implementation or an existing resource, Instant Run performs a cold swap.

Disable Instant Run

To disable Instant Run:

  1. Open the Settings or Preferences dialog.
  2. Navigate to Build, Execution, Deployment > Instant Run.
  3. Uncheck the box next to Enable Instant Run.


반응형

댓글