Android studio application does not launch on the emulator. We assemble and launch the project


1. You need to install the JDK ( Java Development Kit) and JRE (Java Runtime Environment).
Earlier Android SDK only supported JDK version 6, but that is now a thing of the past. Supports 7 and even 8 (according to at least, it was the 8th version that I indicated as JAVA_HOME and in settings Android Studio, and did not experience any problems).
The JRE is needed to run the studio itself. I'm using version 7.
You can download JDK and JRE versions greater than 6 from the Oracle website.

Variable JAVA_HOME Now, it seems, there is no need to install it, since in Android Studio we will specify the path to the JDK in the settings. But I installed it. To do this you need:

  • Go to , select left , in the dialog that opens, find the button Environment Variables.
  • Create a system or user variable JAVA_HOME and specify the path to the JDK for it. I have this path: C:\Program Files\Java\jdk1.8.0_05.
2. If you have Android SDK installed.
Android Studio comes with its own Android SDK. And, if you want to use it, then in some cases strange things can happen. For example, when updating the SDK via SDK Manager, some files were written to an old folder, and problems arose when I deleted this folder. Most likely this happened due to the fact that the registry stored a key with the path to old folder. Therefore, it makes sense to clean the registry. To do this you need to run regedit.exe and find HKEY_LOCAL_MACHINE\Software\Android SDK Tools for 32-bit machines or HKEY_LOCAL_MACHINE\Software\Wow6432Node\Android SDK Tools for 64-bit machines and remove Android SDK Tools. If there are no such keys in the registry of your system, then everything is in order.

If you have installed environment variable ANDROID_SDK_HOME and you want it to point to old installation, then, in theory, this should not be a problem, since when setting up Android Studio we will point it to the path to the SDK. Problems may arise if this variable is used by any of the applications included in the Android SDK.

3. Now let's move on to Android installation Studio.
You need to download Android Studio for your system from the official page and install it. By default, if you select “Install for me only” it is placed in \Users\ \AppData\Local\Android\android-studio\, otherwise put in \Program FIles (x86)\Android\android-studio\. You can also select another folder.

After installation, launch Android Studio.

We see this dialogue


In it we do the following:

Creating a Project

1. New Project
Click New Project.

The following dialogue appears


In it you can configure:
  • Project name (I left it as default: My Application)
  • Company domain, default .example.com, in my case markedone.example.com
  • The package name can also be edited by clicking on Edit on right. By default, it is generated from the project name and company domain and looks like com.example. .<имя проекта в lowercase без пробелов>, я его изменил на com.example.markedone.myapp.
  • The path where the project will be saved. I specified my folder for all sorts of test projects.
When everything is entered, click Next.
2.Form Factors
In this dialog, select target platforms and APIs.

The dialogue looks like this


Here I left everything as default: Phone and Tablet and 4.0.3 IceCreamSandwich. If the API is not installed for some platforms, the message Not Insatlled is displayed. For example, as you can see in the screenshot, I do not have the libraries for Google Glass installed (this can be done through the SDK Manager).

Also pay attention to Help me choose, cool stuff

If you press Help me choose, then this interesting dialogue will open


It contains information on device coverage when choosing a particular API version. The rectangles of API versions are clickable, and a list of the functionality available in them will be displayed on the right. For example, for the default Ice Cream Sandwich:



Click Next.
3.Add Activity

On the next screen we are asked to select Activity


Naturally, I couldn’t pass up Fullscreen Activity and chose it. You can choose another Activity, but in this case the Java sources will be different, and you will have to add a native method call from Java yourself (however, there is nothing complicated about it).
Make a choice, click Next.

The following dialog appears


Here we are asked to configure the Activity.
  • Activity Name- class name, I left it as default: FullscreenActivity.
  • Layout Name- the name layout, for the UI editor, is also left as default.
  • Title- FullscreenActivity is offered by default, I put a space: Fullscreen Activity.
Click Finish.

As a result, the project should open

Build and launch

1. Build the project
We start the assembly through the menu: Build->Make Project(Icons and hotkeys are indicated for menu items, so it will not be difficult to understand them).
During my first build I got an error:

This happened in the file MyApplication/app/build.gradle
To understand what's going on, just hover your cursor over the underlined line:


It’s simple, version 19 is indicated here, but we only have 20 installed, and in the project settings we specified 20 as the target. Let's just change the number:


Apparently, the studio is not satisfied with this, and offers to install an even newer version. But we don't need this now.

Let's launch again Build->Make Project. This time I got everything together. I hope you do too.

2. Setup virtual device
In order to run the program in the emulator, you need to configure a virtual device. Let's go to Tools->Android->AVD Manager(this, like SDK Manager, is a utility from the Android SDK). We need the first tab, Android Virtual Device, it is open by default. On the right we find the button Create... and press it.

The virtual device settings dialog will appear.



At the bottom of the dialog you will see what mistake you made during setup. For example, spaces cannot be entered in the device name, and some fields are required. When there is no inscription below, everything is entered correctly. Click OK.

The device appears in the list


A few words about the Device Definitions tab


Available devices are specified on it (those that are then displayed in the drop-down list Device when creating a new virtual device). To create a new device, you need to click on the button Create Device... and take care of filling out the following dialog:



Close AVD Manager and return to the main Android Studio window.
3. Run on an emulator
We carry out Run->Run "app".
You will have to wait until the project is built to launch.

Finally, the device selection window will appear


Here the only available option to choose from is our virtual device. It’s offered to us right away, so just click OK.

The emulator starts up, it takes quite a long time


Can be opened Tools->Android->Android Device Monitor(a utility from the Android SDK) to see logs from the emulator. It should automatically pick up the virtual device and immediately start outputting logs.

Android Device Monitor


But after launching the emulator, the application did not open for me the first time, I had to click again Run->Run "app".

A slightly changed dialogue appeared

Here the device has moved from the list to be launched to the list of already launched ones. This list, of course, also includes real devices.

After that, things went well, and the application installed and launched pretty quickly.

Full screen mode

And if you tap on the application, it looks like this

This is not system behavior; the click is processed in the application (FullscreenActivity.java file):
// Set up the user interaction to manually show or hide the system UI. contentView.setOnClickListener(new View.OnClickListener() ( @Override public void onClick(View view) ( if (TOGGLE_ON_CLICK) ( mSystemUiHider.toggle(); ) else ( mSystemUiHider.show(); ) ) ); After launch, Android Studio prompted me to turn off Android Device Monitor in order to integrate the output directly into the IDE.

This is what integration looks like

4. Launch in Debug mode
Run->Debug "app"

Again the familiar dialogue

We are waiting for the application to launch and the debugger to connect. I set a breakpoint when the Dummy Button is clicked.

Android Studio in debug


A little annoying is the lack of panels with all sorts of Step Into, Step Out etc.

All this is in the Run menu

5. Launch on 4.0.3
During the process of building and running the project, you may have noticed that we created an application that was compatible with version 4.0.3, but only ran it on the latest version of Android. We'll fix that now. To do this you need to install version 4.0.3 via Tools->Android->SDK Manager.

The necessary items are marked with check marks in the screenshot.


This SDK Platform, ARM EABI v7a System Image And Intel x86 Atom System Image. In fact, we were running an ARM emulator, and we don’t need to install Intel now. I installed it purely because it is also installed for Android L.
Now let's create another device for the new old version of Android (or you can edit the old one).

New device settings


Launch ( Run->Run "app").

In the dialog, select a new device to launch


And let's see what the new emulator looks like - it's clearly more brutal.

Launch

Full screen mode

After clicking

5. Launch on device
Before we get started with the NDK, let's run the project on a real device. I'll run it on my phone

Huawei Ascend G300 with Android 4.0.3


The first thing you need to do is install the adb driver. Everything is quite simple for me, the driver is located directly on the phone, the only thing you need to do is plug the cord into the computer, go to the mounted disk and run the executable file, which will install the adb driver. For other devices, things may be more complicated. For example, for the Prestigio tablet I once had to register the Vendor ID in a special file (so that the standard driver from Google would be used), Samsung needed their own Kies, there was a separate driver for HTC, and so on. In general, you will have to figure out how to install the driver for your device yourself.

After the driver has been installed, you need to enable USB debugging on the device. On my phone to do this I need to go to Settings->For Developers->USB Debugging. But for different devices, as well as builds and versions of Android, the location of this menu item may differ.

Now the phone will have the Android SDK, and the applications being developed will be installed. However, for Huawei this is not all: there are no logs coming from the phone, you need to enable them.

How to enable logs on Huawei

Dial as phone number: *#*#2846579#*#*
The service menu will appear.
Go to ProjectMenu->Background Setting->Log Setting
Open Log switch and install there ON.
Open Log level setting and set the logging level you need (I set verbose).
Reboot your phone.


Now you can run the application on your device: Run->Run "app"

A real device appears in the device selection dialog


Let's launch on the phone.

Launch result.

Application in portrait:

Application in landscape:

Installing and configuring Android NDK

1. Installation of NDK
The Android SDK, as we have already found out, is included in the Android Studio kit, but the NDK is not. Download the NDK suitable for your system from here. Unpack the archive and put it in some folder, for example, in D:\ndk, so that the file ndk-build.cmd lay right in it. Important: It is necessary that there are no spaces in the path to the NDK.
2. Add the ANDROID_NDK_HOME variable
Let's go to Control Panel\System and Security\System, select on the left Advanced System Settings, in the dialog that opens, click the button Environment Variables. Create a variable with the name ANDROID_NDK_HOME and meaning D:\ndk(path to your NDK).

Alternatively, instead of specifying a global variable, you can specify the path to ndk in the file local.properties of your project (directly in the root folder: MyApplication\local.properties). The contents of the file will look something like this (pay attention to the double backslashes, as this is critical for Windows):
## This file is automatically generated by Android Studio. # Do not modify this file -- YOUR CHANGES WILL BE ERASED! # # This file should *NOT* be checked into Version Control Systems, # as it contains information specific to your local configuration. # # Location of the SDK. This is only used by Gradle. # For customization when using a Version Control System, please read the # header note. sdk.dir=C:\\Users\\ \\AppData\\Local\\Android\\android-studio\\sdk ndk.dir=D:\\ndk
Don't believe the disclaimer that says "your changes will be thrown away" in this case this is wrong. Please note that it is recommended to exclude this file from version control as it only contains information local to the user. For a change, they didn't lie to us about this. Well, of course, this change will not affect your other projects in any way. When installed ANDROID_NDK_HOME It is not necessary to specify the path in local.properties.

3. Let's install the necessary Android version API
Go to NDK\platforms(I have this D:\ndk\platforms) and see the maximum version of the available APIs. In my case, the maximum version is 19. But at the same time, we only have versions 20 and 15 installed in the SDK. So we go to the SDK Manager and download SDK Platform version 19, otherwise nothing will work.

What to download

4. Configure gradle to work with NDK
I took the information from samples, you can download them. I downloaded samples for version 0.11. I took ndkSanAngeles as the main example.

How to run ndkSanAngeles

After the samples are downloaded, they need to be unpacked. Then you need to open the ndkSanAngeles project. For Android Studio, a project is a folder, so you need to open it. To do this we perform File->Open, or, if you are in the Welcome dialog, Open Project. We look for the ndkSanAngeles folder through the file open dialog.

After opening the project, you should look at the file build.gradle. Here's the original:
buildscript ( repositories ( mavenCentral() ) dependencies ( classpath "com.android.tools.build:gradle:0.11.0" ) ) apply plugin: "android" android ( compileSdkVersion 19 buildToolsVersion "19.1.0" defaultConfig ( ndk ( moduleName " sanangeles" cFlags "-DANDROID_NDK -DDISABLE_IMPORTGL" ldLibs "GLESv1_CM", "dl", "log" stl "stlport_static" ) // This actual the app version code. Giving ourselves 1,000,000 values ​​versionCode = 123 ) buildTypes.debug.jniDebugBuild true productFlavors ( x86 ( ndk ( abiFilter "x86") // this is the flavor part of the version code. // It must be higher than the arm one for devices supporting // both, as x86 is preferred. versionCode = 3 ) arm ( ndk ( abiFilter "armeabi-v7a" ) versionCode = 2 ) mips ( ndk ( abiFilter "mips" ) versionCode = 1 ) fat ( // fat binary, lowest version code to be // the last option versionCode = 0 ) ) // make per-variant version code applicationVariants.all ( variant ->
And here is a modified version so that the project can be assembled from me:
buildscript ( repositories ( mavenCentral() ) dependencies ( classpath "com.android.tools.build:gradle:0.12.+" ) ) apply plugin: "android" android ( compileSdkVersion 19 buildToolsVersion "20.0.0" defaultConfig ( ndk ( moduleName " sanangeles" cFlags "-DANDROID_NDK -DDISABLE_IMPORTGL" ldLibs "GLESv1_CM", "dl", "log" stl "stlport_static" ) // This actual the app version code. Giving ourselves 1,000,000 values ​​versionCode = 123 ) buildTypes.debug.jniDebugBuild true productFlavors ( x86 ( ndk ( abiFilter "x86") // this is the flavor part of the version code. // It must be higher than the arm one for devices supporting // both, as x86 is preferred. versionCode = 3 ) arm ( ndk ( abiFilter "armeabi-v7a" ) versionCode = 2 ) mips ( ndk ( abiFilter "mips" ) versionCode = 1 ) fat ( // fat binary, lowest version code to be // the last option versionCode = 0 ) ) // make per-variant version code applicationVariants.all ( variant -> // get the single flavor def flavorVersion = variant.productFlavors.get(0).versionCode // set the composite code variant.mergedFlavor.versionCode = flavorVersion * 1000000 + defaultConfig. versionCode ) )
The changes are as follows:

  • About the gradle plugin version mismatch ( classpath "com.android.tools.build:gradle:0.11.0") will be said when you try to build and offer the correct version number. For me it is 0.12.+.
  • compileSdkVersion 19 remains as it is the maximum version for the current NDK.
  • buildToolsVersion changed to 20. Installed versions can be viewed in the SDK Manager, and others can be installed there.
After this, ndkSanAngeles should reassemble. Be careful and check the versions you have installed.

In our project, we need to select the correct build.gradle file, since there are two of them. The thing is that MyApplication is a project, and app is a project module (or subproject), and they have their own build.gradle for each. First let's look at the project file

MyApplication->build.gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript ( repositories ( jcenter() ) dependencies ( classpath "com.android.tools.build:gradle:0.12.+" // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files ) ) allprojects ( repositories ( jcenter() ) )


From the comments in the code it is clear that we need a module file

MyApplication->app->build.gradle

apply plugin: "com.android.application" android ( compileSdkVersion 20 buildToolsVersion "20.0.0" defaultConfig ( applicationId "com.example.markedone.myapp" minSdkVersion 15 targetSdkVersion 20 versionCode 1 versionName "1.0" ) buildTypes ( release ( runProguard false proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro" ) ) ) dependencies ( compile fileTree(dir: "libs", include: ["*.jar"]) // You must install or update the Support Repository through the SDK manager to use this dependency. //compile "com.android.support:support-v4:19.+" compile "com.android.support:support-v4:20.+" )


Let's configure it to work with NDK, using build.gradle from ndkSanAngeles as a “donor”.

First, let's replace
compileSdkVersion 20
on
compileSdkVersion 19
since NDK is limited to version 19.

IN defaultConfig we will add settings ndk, and also replace targetSdkVersion at 19:
defaultConfig ( applicationId "com.example.markedone.myapp" minSdkVersion 15 targetSdkVersion 19 versionCode 1 versionName "1.0" ndk ( moduleName "myapp" cFlags "-DANDROID_NDK" ldLibs "log" stl "stlport_static" ) ) NDK settings include

  • moduleName- module name, will be used to name the *.so file
  • cFlags- C flags
  • ldLibs- libraries that you want to connect to native code
  • stl- STL library version
In buildTypes we will enable the JNI debug assembly for debug:
buildTypes ( release ( runProguard false proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro" ) debug.jniDebugBuild true )
Now let's add productFlavors. Here we indicate which *.so libraries to include in the build for a specific architecture. Thus, *.apk compiled for arm will contain a version of the library only for arm, for x86 - for x86, and so on. This piece is completely copied from ndkSanAngeles. Explanation of meanings versionCode from the comments: for x86 we set the maximum value versionCode, since if the device supports both x86 and arm, then the x86 assembly is preferable (apparently, since it has a larger version, it will be installed), and the minimal versionCode prescribed for fat(in theory, this should be a “thick” *.apk, containing all possible versions of the libraries at once).
productFlavors ( x86 ( ndk ( abiFilter "x86" ) // this is the flavor part of the version code. // It must be higher than the arm one for devices supporting // both, as x86 is preferred. versionCode = 3 ) arm ( ndk ( abiFilter "armeabi-v7a" ) versionCode = 2 ) mips ( ndk ( abiFilter "mips" ) versionCode = 1 ) fat ( // fat binary, lowest version code to be // the last option versionCode = 0 ) )
“Collecting” the meaning versionCode for each build option:
// make per-variant version code applicationVariants.all ( variant -> // get the single flavor def flavorVersion = variant.productFlavors.get(0).versionCode // set the composite code variant.mergedFlavor.versionCode = flavorVersion * 1000000 + defaultConfig.versionCode)
Finally, the last section, dependencies. If you remember, here we changed compile "com.android.support:support-v4:19.+" on compile "com.android.support:support-v4:20.+", to build with the only version of the library installed on us. Now you have to change it back to 19.
dependencies ( compile fileTree(dir: "libs", include: ["*.jar"]) // You must install or update the Support Repository through the SDK manager to use this dependency. compile "com.android.support:support- v4:19.+" )

Full listing of the modified build.gradle file

apply plugin: "com.android.application" android ( compileSdkVersion 19 buildToolsVersion "20.0.0" defaultConfig ( applicationId "com.example.markedone.myapp" minSdkVersion 15 targetSdkVersion 19 versionCode 1 versionName "1.0" ndk ( moduleName "myapp" cFlags " -DANDROID_NDK" ldLibs "log" stl "stlport_static" ) ) buildTypes ( release ( runProguard false proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro" ) debug.jniDebugBuild true ) productFlavors ( x86 ( ndk ( abiFilter "x86" ) // this is the flavor part of the version code. // It must be higher than the arm one for devices supporting // both, as x86 is preferred. versionCode = 3 ) arm ( ndk ( abiFilter "armeabi -v7a" ) versionCode = 2 ) mips ( ndk ( abiFilter "mips" ) versionCode = 1 ) fat ( // fat binary, lowest version code to be // the last option versionCode = 0 ) ) // make per-variant version code applicationVariants.all ( variant -> // get the single flavor def flavorVersion = variant.productFlavors.get(0).versionCode // set the composite code variant.mergedFlavor.versionCode = flavorVersion * 1000000 + defaultConfig.versionCode ) sourceSets ( main ( jni.srcDirs = ["src/main/jni", "src/main/jni/"] ) ) ) dependencies ( compile fileTree(dir: "libs", include: ["*.jar"]) // You must install or update the Support Repository through the SDK manager to use this dependency. compile "com.android.support:support-v4:19.+" )

5. Create the jni folder
We will save C/C++ files in the jni folder. This is what NDK expects from us. We need to create a folder in MyApplication/app/src/main. This can be done directly from Android Studio, and in two ways.
Firstly, you can right-click on main and simply create a folder via

New->Directory


Secondly, you can use a special menu item

New->Folder->JNI Folder

It launches the folder creation wizard




In the first dialog we select for which part of the module the jni folder will be created, and in the second we can change its location.

6. Add C++ files
There is no wizard for C++ files, so to create a file we right-click on the folder jni and choose

New->File


First, let's create a header file myapp.h:
#pragma once #include #ifdef __cplusplus extern "C" ( #endif JNIEXPORT jstring JNICALL Java_com_example_markedone_myapp_FullscreenActivity_stringFromJNI(JNIEnv* env, jclass clazz); #ifdef __cplusplus ) #endif

Description

  • #pragma once - instead of the standard (#ifndef/#define/#endif) protection against re-enablement. Now #pragma once is understood by most C++ compilers.
  • #include - include the JNI header so that you can use the types declared there.
  • #ifdef __cplusplus ... #endif - the code inside will be compiled only in C++ (but not in C).
  • extern "C" ( ... ) - get rid of name mangling (what is it and why, ).
  • JNIEXPORT jstring JNICALL Java_com_example_markedone_myapp_FullscreenActivity_stringFromJNI(JNIEnv* env, jclass clazz); - declaration of the function that we will implement.
    Let's look at this ad in more detail.
    • JNIEXPORT necessary for proper linking.
    • JNICALL for the correct calling convention.
    • jstring- the return type of the function, in this case a string compatible with the Java string.
    • Java_com_example_markedone_myapp_FullscreenActivity_stringFromJNI- function name, consists of:
      Java- the language that evokes.
      com_example_markedone_myapp- this is the application id ( com.example.markedone.myapp).
      FullscreenActivity is the name of a Java class that contains a method declaration representing a native function.
      stringFromJNI- actually, the name of the function (this is how it will be in Java).
    • JNIEnv* env, jclass clazz - required parameters passed from Java.
      JNIEnv* env is a pointer to an object representing the JNI environment.
      jclass clazz is the class that owns the native method declaration in Java. Here we need to make a reservation that jclass clazz is for static native ( static native) method. For a non-static method you will need to write jobject obj .

Now let's create an implementation file, myapp.cpp. In it we will write the following code:
#include #include #include "myapp.h" JNIEXPORT jstring JNICALL Java_com_example_markedone_myapp_FullscreenActivity_stringFromJNI(JNIEnv* env, jclass clazz) ( std::string tag("GREETING"); std::string message("Hello from C++!"); __android_log_print(ANDROID_LOG_INFO, tag .c_str(), "%s", message.c_str()); std::string jniMessage("Hello from JNI!"); return env->NewStringUTF(jniMessage.c_str()); )

Description

  • #include - connect the log, for which we even added the library ( ldLibs "log")
  • #include - for std::string, which we use to check for the presence of STL.
    #include "myapp.h" - we include our header file.
    JNIEXPORT jstring JNICALL Java_com_example_markedone_myapp_FullscreenActivity_stringFromJNI(JNIEnv* env, jclass clazz) ( ... ) - implement the function declared in "myapp.h".
    std::string tag("GREETING"); std::string message("Hello from C++!"); - create lines for output to the log.
    __android_log_print(ANDROID_LOG_INFO, tag.c_str(), "%s", message.c_str()); - output to log. Please note that you need to specify 4 parameters: the type of message in the log, the tag, the string format, and, finally, the message itself.
    std::string jniMessage("Hello from JNI!"); - the string that we will pass to Java.
    return env->NewStringUTF(jniMessage.c_str()); - return value, using JNIEnv we create a jstring from a C-string. Note that we don't need a construct like (*env)-> since we're writing in C++, not C.
Now we will create another file: stub.cpp, and leave it empty. The fact is that if you leave only one *.cpp file in the jni folder, then ndk-build will generate the error “no rule to make target”.
7. Add a native function call from Java
Open the file MyApplication/app/src/main/java/com.example.markedone.myapp.FullscreenActivity. In fact, it has a java extension, and com, example, markedone and myapp are folders, but Android Studio hides this.

File contents

package com.example.markedone.myapp; import com.example.markedone.myapp.util.SystemUiHider; import android.annotation.TargetApi; import android.app.Activity; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.view.MotionEvent; import android.view.View; /** * An example full-screen activity that shows and hides the system UI (i.e. * status bar and navigation/system bar) with user interaction. * * @see SystemUiHider */ public class FullscreenActivity extends Activity ( /** * Whether or not the system UI should be auto-hidden after * (@link #AUTO_HIDE_DELAY_MILLIS) milliseconds. */ private static final boolean AUTO_HIDE = true; /* * * If (@link #AUTO_HIDE) is set, the number of milliseconds to wait after * user interaction before hiding the system UI. */ private static final int AUTO_HIDE_DELAY_MILLIS = 3000; /** * If set, will toggle the system UI visibility upon interaction. Otherwise, * will show the system UI visibility upon interaction. */ private static final boolean TOGGLE_ON_CLICK = true; /** * The flags to pass to (@link SystemUiHider#getInstance). */ private static final int HIDER_FLAGS = SystemUiHider.FLAG_HIDE_NAVIGATION; /** * The instance of the (@link SystemUiHider) for this activity. */ private SystemUiHider mSystemUiHider; @Override protected void onCreate(Bundle savedInstanceState) ( super.onCreate(savedInstanceState); setContentView(R.layout .activity_fullscreen); final View controlsView = findViewById(R.id.fullscreen_content_controls); final View contentView = findViewById(R.id.fullscreen_content); // Set up an instance of SystemUiHider to control the system UI for // this activity. mSystemUiHider = SystemUiHider.getInstance(this, contentView, HIDER_FLAGS); mSystemUiHider.setup(); mSystemUiHider .setOnVisibilityChangeListener(new SystemUiHider.OnVisibilityChangeListener() ( // Cached values. int mControlsHeight; int mShortAnimTime; @Override @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2) public void onVisibilityChange(boolean visible) ( if (Build.VERSION.SDK_INT > = Build.VERSION_CODES.HONEYCOMB_MR2) ( // If the ViewPropertyAnimator API is available // (Honeycomb MR2 and later), use it to animate the // in-layout UI controls at the bottom of the // screen. if (mControlsHeight == 0) ( mControlsHeight = controlsView.getHeight(); ) if (mShortAnimTime == 0) ( mShortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime); ) controlsView.animate() .translationY(visible ? 0: mControlsHeight).setDuration(mShortAnimTime); ) else ( // If the ViewPropertyAnimator APIs aren't // available, simply show or hide the in-layout UI // controls. controlsView.setVisibility(visible ? View.VISIBLE: View.GONE); ) if (visible && AUTO_HIDE ) ( // Schedule a hide(). delayedHide(AUTO_HIDE_DELAY_MILLIS); ) ) )); // Set up the user interaction to manually show or hide the system UI. contentView.setOnClickListener(new View.OnClickListener() ( @Override public void onClick(View view) ( if (TOGGLE_ON_CLICK) ( mSystemUiHider.toggle(); ) else ( mSystemUiHider.show(); ) ) ); // Upon interacting with UI controls, delay any scheduled hide() // operations to prevent the jarring behavior of controls going away // while interacting with the UI. findViewById(R.id.dummy_button).setOnTouchListener(mDelayHideTouchListener); ) @Override protected void onPostCreate(Bundle savedInstanceState) ( super.onPostCreate(savedInstanceState); // Trigger the initial hide() shortly after the activity has been // created, to briefly hint to the user that UI controls // are available. delayedHide(100); ) /** * Touch listener to use for in-layout UI controls to delay hiding the * system UI. This is to prevent the jarring behavior of controls going away * while interacting with activity UI. */ View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() ( @Override public boolean onTouch(View view, MotionEvent motionEvent) ( if (AUTO_HIDE) ( delayedHide(AUTO_HIDE_DELAY_MILLIS); ) return false; ) ); Handler mHideHandler = new Handler(); Runnable mHideRunnable = new Runnable() ( @Override public void run() ( mSystemUiHider.hide(); ) ); /** * Schedules a call to hide() in milliseconds, canceling any * previously scheduled calls. */ private void delayedHide(int delayMillis) ( mHideHandler.removeCallbacks(mHideRunnable); mHideHandler.postDelayed(mHideRunnable, delayMillis); ) )


Let's add the following code to the FullscreenActivity class:
static ( System.loadLibrary("myapp"); ) private static native String stringFromJNI(); Here the library is loaded first and then the method is declared stringFromJNI, which corresponds to our function in C++. Note that it is declared as static (this affects what (jclass or jobject) will be as the second parameter of the C++ function) and native. There is no need to implement a native method, we have already done this in C++, and JNI will do the rest for us.

Now we, in general, can already call our function. If you, like me, chose FullscreenActivity, then we have a Dummy Button that essentially does nothing. And we even already have a touch listener, although not the best (it will be called many times while the finger is on the screen), but in order not to produce unnecessary code, we use it.

First, let's add to the import list:
import android.widget.Button;
so that you can work normally with the button.

Let's find the following code:
View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() ( @Override public boolean onTouch(View view, MotionEvent motionEvent) ( if (AUTO_HIDE) ( delayedHide(AUTO_HIDE_DELAY_MILLIS); ) return false; ) );
and add a few lines before return false .
View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() ( @Override public boolean onTouch(View view, MotionEvent motionEvent) ( if (AUTO_HIDE) ( delayedHide(AUTO_HIDE_DELAY_MILLIS); ) final String message = stringFromJNI(); final Button button = (Button )findViewById(R.id.dummy_button); final String actualText = button.getText().toString(); if(message.equals(actualText)) ( button.setText("Dummy Button"); ) else ( button.setText (message); ) return false; ) );

Description of the added code

  • final String message = stringFromJNI(); - we get a string from C++. Calling a native method is what it all started for.
  • final Button button = (Button)findViewById(R.id.dummy_button); - find the button object.
  • final String actualText = button.getText().toString(); - pull out the current button text.
  • if(message.equals(actualText)) - compare the string obtained from C++ with the text of the button.
    • button.setText("Dummy Button"); - if they are the same, change the text of the button to Dummy Button.
    • button.setText(message); - if they differ, then we change them to text obtained from C++.

Full class listing of the modified class

package com.example.markedone.myapp; import com.example.markedone.myapp.util.SystemUiHider; import android.annotation.TargetApi; import android.app.Activity; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.view.MotionEvent; import android.view.View; import android.widget.Button; /** * An example full-screen activity that shows and hides the system UI (i.e. * status bar and navigation/system bar) with user interaction. * * @see SystemUiHider */ public class FullscreenActivity extends Activity ( static ( System.loadLibrary("myapp"); ) private static native String stringFromJNI(); /** * Whether or not the system UI should be auto-hidden after * (@link #AUTO_HIDE_DELAY_MILLIS) milliseconds. */ private static final boolean AUTO_HIDE = true; /** * If (@link #AUTO_HIDE) is set, the number of milliseconds to wait after * user interaction before hiding the system UI. */ private static final int AUTO_HIDE_DELAY_MILLIS = 3000; /** * If set, will toggle the system UI visibility upon interaction. Otherwise, * will show the system UI visibility upon interaction. */ private static final boolean TOGGLE_ON_CLICK = true; /** * The flags to pass to (@link SystemUiHider#getInstance). */ private static final int HIDER_FLAGS = SystemUiHider.FLAG_HIDE_NAVIGATION; /** * The instance of the (@link SystemUiHider) for this activity. */ private SystemUiHider mSystemUiHider; @Override protected void onCreate(Bundle savedInstanceState) ( super.onCreate(savedInstanceState); setContentView(R.layout.activity_fullscreen); final View controlsView = findViewById(R.id.fullscreen_content_controls); final View contentView = findViewById(R.id.fullscreen_content); // Set up an instance of SystemUiHider to control the system UI for // this activity. mSystemUiHider = SystemUiHider.getInstance(this, contentView, HIDER_FLAGS); mSystemUiHider.setup(); mSystemUiHider .setOnVisibilityChangeListener(new SystemUiHider.OnVisibilityChangeListener() ( // Cached values. int mControlsHeight; int mShortAnimTime; @Override @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2) public void onVisibilityChange(boolean visible) ( if (Build.VERSION.SDK_INT > = Build.VERSION_CODES.HONEYCOMB_MR2) ( // If the ViewPropertyAnimator API is available // (Honeycomb MR2 and later), use it to animate the // in-layout UI controls at the bottom of the // screen. if (mControlsHeight == 0) ( mControlsHeight = controlsView.getHeight(); ) if (mShortAnimTime == 0) ( mShortAnimTime = getResources().getInteger(android. R.integer.config_shortAnimTime); ) controlsView.animate() .translationY(visible ? 0: mControlsHeight) .setDuration(mShortAnimTime); ) else ( // If the ViewPropertyAnimator APIs aren't // available, simply show or hide the in-layout UI // controls. controlsView.setVisibility(visible ? View.VISIBLE: View.GONE); ) if (visible && AUTO_HIDE ) ( // Schedule a hide(). delayedHide(AUTO_HIDE_DELAY_MILLIS); ) ) )); // Set up the user interaction to manually show or hide the system UI. contentView.setOnClickListener(new View.OnClickListener() ( @Override public void onClick(View view) ( if (TOGGLE_ON_CLICK) ( mSystemUiHider.toggle(); ) else ( mSystemUiHider.show(); ) ) ); // Upon interacting with UI controls, delay any scheduled hide() // operations to prevent the jarring behavior of controls going away // while interacting with the UI. findViewById(R.id.dummy_button).setOnTouchListener(mDelayHideTouchListener); ) @Override protected void onPostCreate(Bundle savedInstanceState) ( super.onPostCreate(savedInstanceState); // Trigger the initial hide() shortly after the activity has been // created, to briefly hint to the user that UI controls // are available. delayedHide(100); ) /** * Touch listener to use for in-layout UI controls to delay hiding the * system UI. This is to prevent the jarring behavior of controls going away * while interacting with activity UI. */ View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() ( @Override public boolean onTouch(View view, MotionEvent motionEvent) ( if (AUTO_HIDE) ( delayedHide(AUTO_HIDE_DELAY_MILLIS); ) final String message = stringFromJNI(); final Button button = (Button)findViewById(R.id.dummy_button); final String actualText = button.getText().toString(); if(message.equals(actualText)) ( button.setText("Dummy Button"); ) else ( button .setText(message); ) return false; ) ); Handler mHideHandler = new Handler(); Runnable mHideRunnable = new Runnable() ( @Override public void run() ( mSystemUiHider.hide(); ) ); /** * Schedules a call to hide() in milliseconds, canceling any * previously scheduled calls. */ private void delayedHide(int delayMillis) ( mHideHandler.removeCallbacks(mHideRunnable); mHideHandler.postDelayed(mHideRunnable, delayMillis); ) )

17. We assemble and launch the project
First Build->Make Project. At this stage, the Java part is assembled.
Then Run->Run "app". And here, before the application starts, the C++ part will be assembled. If there are any errors in it, a message will be displayed about this. If there are no errors, a standard device selection dialog will appear, and after clicking OK the application will launch.

Working on a real device

Outputting a message to the log

Conclusion

Overall, I liked Android Studio. The integration of the Android SDK is done quite tightly, sometimes you even forget that these are separate programs that are launched. There are all sorts of interesting goodies, such as Help me choose. I liked the new build system - Gradle - but there is also a drawback: there is very little information on it.

It is also clear that support for NDK is still damp, but there is movement in this direction. I really hope that they will eventually provide full support for C++ development.

P.S. No C++ code debug has been found yet.

Tags:

  • android studio
  • gradle
  • android ndk
  • android
Add tags

Android - free operating system, based on Linux with a Java programming interface.

If you have a desire to develop applications for phones under Android control, then you need to carefully prepare and install all the necessary tools for the job.

Installing Android Studio

Articles are often reworked as some things quickly become outdated. But I can’t keep track of everything, so you’ll have to figure things out on your own if you encounter differences.

It is important to understand that the application itself is written in Java (and now also in Kotlin), and the development environment is chosen to suit your taste. What can be done in Android Studio (or its big brother IntelliJ IDEA), can be done in Eclipse and other editors. Although since 2016 official support Eclipse has stopped.

You can download the installation package for the studio from the page https://developer.android.com/studio/index.html

The installation itself should not cause any problems. Installation package includes the required minimum. Sometimes you need to launch Android SDK Manager and check for new SDK versions through the menu Tools | Android | SDK Manager:

Over time, you will figure out for yourself what you need to install and what is not necessary. At first, agree to the terms that the manager offers you by default.

A user from Bulgaria wrote that Win64 requires administrator rights when installing or updating. Keep in mind. On a clean system it didn’t ask me anything.

In studio version 2.3 (maybe earlier) the OpenJDK package is installed, which is an alternative to the JDK from Oracle. There is a note in the studio settings that OpenJDK is the recommended option, although you can specify the path to the standard JDK. In any case, you will have Java 8 no matter which option you choose.

Creating emulators

To debug applications, we use a phone emulator - a virtual machine on which our application will run. You can also use a real device.

Now, at the time of installation, the studio creates one device for the emulator. If this is not the case, you can always install manually. You can also add other devices under different versions Android, screen resolutions, etc.

To create a phone emulator, select from the menu Tools | Android | AVD Manager. When you launch it for the first time, a wizard dialog box will appear.

Press the button Create a virtual device and in a new window we see a set of possible emulators, including for watches. Download the necessary emulators. For starters, one emulator is quite suitable.

Enter any friendly name, for example, Android4. Choose the required version Android, screen size, etc.

If necessary, you can create emulators for each OS version and check the program for functionality. The remaining settings can be left unchanged. You can always go back to the settings and edit again. It is often recommended to use the option Use Host GPU to take advantage of opportunities GPU. This increases the speed of the emulator. Press the button OK.

Added emulators will be stored in the emulator manager.

If you have created several emulators, then select the one you need and press the button with a green triangle to launch the emulator. The pencil icon allows you to edit settings. But usually the emulator is not launched separately. When you launch the application, the studio itself will offer to launch the emulator.

remember, that virtual machines by default they are saved in the user's folder, and the folder paths should not contain Russian characters to avoid problems.

If you still fall into this trap, then I will give a link to change the user folder to English: http://www.cherneenet.ru/lokalnaj_zapis.html (thanks to reader Evgeny Stepanov for the hint). You can also correct the ini file and write the path to the virtual device in such a way that there are no Russian letters in the path (accordingly, the *.avd file itself also needs to be moved to another location).

Depending on the power of your computer, you may need to wait a little while for the emulator to load first. The Intel emulator loads much faster. You can also use a real phone. I usually use old phone and an emulator for new versions of Android.

Testing on a real device

It is advisable to test the final version of the application on a real device. Starting with Android 4.4, you need to activate developer mode on your device (tablet, phone, watch). To do this, go to Settings, open the “About phone” page and click seven times on the line with the build number Build number. After this, a new item will appear in the settings For developers or something like that if the manufacturer uses its own shell.

Once you open the developer page, you need to enable USB debugging. I also include the option Don't turn off the screen. Some devices require a separate driver to be installed; look for information on the manufacturer's website.

Working in terminal mode

Studio also allows you to run command line commands in separate window. For convenience, you should slightly customize the system for yourself.

I have a non-localized one installed Windows version, so some of the points will be given in English.

For Windows 7/8 open Control Panel | System, press the button Advanced System Settings. In the new window, click the button Environment Variables.

Find the variable Path on the list System variables

Click on the button Edit to edit a variable. Add a semicolon at the end of the line and then specify the folder paths platform-tools And tools, which are included in the SDK. In my case it turned out like this:

;D:\Android\SDK\platform-tools;D:\Android\SDK\tools

Close all windows (better to reboot). Check if everything is working correctly. Run command line and enter the command:

Echo %path%

You should see a line listing all the paths included in the variable Path, including yours.

For the following check, enter the command:

A list of command parameters will appear.

Also try the command:

The SDK Manager window will open.

If you wrote something wrong, the commands will not be recognized and you need to correct the error in writing the path.

Now let's do these operations in the studio itself. Launch studio and open the project (see next lesson). There is a tab at the bottom of the status bar. Switch to it. In a terminal window, enter either of the previous two commands.

Documentation

The latest documentation can always be found at developer.android.com. If you have problems with the Internet, then in the subfolder /docs in your folder installed Android SDK, you can find its local copy (if you did not refuse to install it).

Cat installation

This point is not mandatory, but as practice shows, having a cat allows you to achieve quick results V learning Android. You can pick up a cat on the street, adopt it from a shelter, or buy it through an advertisement. Any kind will do - red, striped, black. The cat should be washed, fed and placed nearby. Your karma is growing at this time and the process of mastering the material will go faster.

Preparations for development have been completed. Now the next step is creating the first application.

Sit back and fasten your seat belts - an exciting journey into the world of Android application development awaits us.

When you begin to master development for any platform, you are sure to immediately come across many pitfalls that are invisible at first glance. Most of them will be related to the coding process itself: inconsistencies in the API, hidden functions, limitations, special programming style for the platform. There are also stones that lie a little further away: testing and automatic optimization, creating clipart and icons, receiving automatic crash reports. Inexperienced Android developers run the risk of getting both their feet cut.

In this article, we'll look at Android development issues in the context of utilities and tools. We will get rid of the need to connect the smartphone using a cable during testing and debugging on the device, we will split the application into Lite versions and Pro, we will build into it a mechanism for automatically generating and sending crash reports to the server, automate testing, obfuscate and optimize the code, and also create an icon and all the necessary resources for the application in a few minutes. Go.

1. Slow emulator

So, you've sketched out your first application, and it's time to launch it and test its functionality. For this purpose, the Android SDK includes an emulator. For a long time he was reproached for being slow, but with the release of Android Studio 2.0 the situation has improved significantly - the x86 version of the emulator received hardware acceleration, so now it works faster than real devices. In addition, it has a convenient graphical interface with which you can simulate calls, SMS, change GPS data and network failures, that is, everything for which you previously had to use command line tools.

Therefore, if you haven't upgraded yet, I highly recommend doing so, not to mention switching from Eclipse. And be sure to select the x86 version of the emulator in the AVD manager; the ARM version does not support hardware acceleration.

2. Smartphone on a leash

The second stage is testing on a real device. Everything is simple here: you connect your smartphone via USB, install the drivers, enable debugging mode in the developer settings, after which the device appears in the list of applications available for installation (next to the emulator). The only problem is that in this case the device must be kept connected to the PC using a cable, and if this is your main smartphone that receives calls and messages, then there is no need to talk about convenience.

Luckily, Android Studio (more specifically, the ADB utility it uses to communicate with the device) supports networking. But this function still needs to be activated. If you have a rooted smartphone, then you're in luck: you can enable network debugging using the WiFi ADB application. Sequencing:

  1. Install WiFi ADB, launch it, enable network mode using the switch and remember the IP address.
  2. Launch Android Studio.
  3. Open the console, go to the directory with the installed SDK, then go to platform-tools and run next command:

    $ adb connect IP address

Now, if you try to build and launch the application, you will also see your smartphone in the list of devices. Those who are not root can restart ADB in network mode, after connecting it with a cable. This is done like this:

  1. We connect the smartphone and install drivers.
  2. Enable debugging mode in the developer settings.
  3. Open the console, go to the SDK/platform-tools directory and run the following command:

    $ adb tcpip 5555

  4. Connect to the smartphone via the network:

    $ adb connect IP address

The IP address can be found through the settings: “About phone (About tablet) → General information", item "IP address".

3. Libraries

Okay, your hack that you threw together in half an hour seems to be working, and it’s time to turn it into a real application with a beautiful interface and widgets for your desktop. At this stage, you will probably need external libraries that implement various interface concepts, programming patterns and communication with external services. And if everything is clear with the latter (you need an SDK for Dropbox - you open the portal for developers and follow the instructions), then with the rest it is already more difficult. Where to look for them and which libraries are better?

The most comprehensive library catalog is Android Arsenal. There you will find almost everything you need. Available convenient search and sorting by rating, for each library there are instructions on how to connect it to your project, including using the standard Gradle build system for Android: just add the repository to the project’s build.gradle file and specify the library in the list of dependencies.


You can find an excellent list of must-have libraries on this page. On my own behalf, I’ll add that in the first stages you should immediately study Dagger 2, RxJava And Retrofit. As you become an advanced developer, you will come to use these libraries one way or another.

4. Icons and clipart

Finally, after days or weeks, a full-fledged application begins to emerge. But there is still no graphic material: the icon is standard, in the shape of a green robot, instead of clipart there are placeholders. Obviously, without graphics there is no point in going to the markets, but paying for an icon for your first application is also stupid. What to do?

In fact, the icon can be generated. There is a wonderful web service Android Asset Studio, with which in just a couple of minutes you will get a beautiful icon in all possible resolutions. As a basis, you can take a picture you prepared, simply write text, or, best of all, choose from the clipart provided by the service. You can also set the icon style (round, square, etc.) iOS style...), color, adjust shadows and other parameters. As a result, you will have the archive ic_launcher.zip at your disposal, which must be deployed to the AndroidstudioProjects/APP_NAME/app/src/main/res directory. Be sure to create a web icon by clicking on the “Generate web icon” button. You'll need it.


The same service allows you to create icons for the ActionBar and status bar. The principle is approximately the same, I will only say that icons with an indentation of 15% from the edges look best in the status bar.

In addition, you will need the so-called Feature Image. This is a special picture that Play Market and other application stores are used as a bar at the top of the screen (when you open the application page on a smartphone). It can be generated using another service. To take screenshots, you can use the official service from Google. It creates a smartphone frame around the screenshot.

5. Crash reports

The application is ready, there is an icon, the interface is convenient, the code is high-quality. It's time for testing, and the first thing you do is send the application to your friends and acquaintances. But here’s the problem: for some of them the application crashes, but for you everything works fine, and you cannot repeat the actions that led to the crash. What should you do, ask your friends to send you a logcat listing?

No, we need a crash reporting system. There are a huge number of them, and they all implement the same principle of operation: a small library is connected to the application, which, at the moment of the fall, records the stack trace and other data about the fall and sends it to the server, and then a special web interface creates beautiful images based on them and visual reports.

One of the most popular such systems is Fabric, but I recommend looking towards Splunk MINT: it is free, simple and easily integrated into the application (just add one line of code). To start using it, you need to connect the SDK to the project; this can be done using the same Gradle. Open the build.gradle file (the one that applies to the application, not the entire project) and add the following lines:

Repositories ( maven ( url "https://mint.splunk.com/gradle/" ) ) dependencies ( compile "com.splunk.mint:mint:5.0.0" )


After this, Splunk MINT will show you the line of code that needs to be inserted into the code:

Continuation is available only to subscribers

Option 1. Subscribe to Hacker to read all materials on the site

Subscription will allow you to read ALL paid materials on the site within the specified period. We accept payment bank cards, electronic money and transfers from mobile operator accounts.

Let's create an android emulator for testing while writing applications. Last time we configured the SDK in the Android Studio environment, updated versions and Android OS packages. However, you can use a real device: phone, tablet.

Creating an Android emulator, setting up an Android emulator

Sometimes this is justified, for example if you are creating android apk for myself. On the phone, enable developer mode in the menu, connect the device via USB cable to the computer, and during assembly the application will be installed on the smartphone, test for health. You can test via WIFI, via adb, I personally installed it on my phone A.D.B. Wireless Pro 1.9.2,

when starting I chose the type wifi connections, and on the computer in total commander, in the plugins section I launched A.D.B. ,

specified ip and port,

and connected.

Further Android Studio I installed the tested apk on my phone via wifi. It is possible through the console, but “this is not our method.” Why is it needed? Android emulator , you ask? And then, there’s just a whole zoo of Android versions and device models, and there are more and more every day. Imagine if you need to write for an “old” model of phone or tablet, but you don’t have it in stock, don’t buy it. This method is suitable for large companies professionally developing applications for Android, with a budget tending to infinity. We, from simple, small-scale households, will use an emulator; to a certain extent, it provides the opportunity to select versions and models of androids, although it eats up a lot of memory..

Let's launch Android Studio , V top menu click Tools->Android->AVD Manager,

in it, click the button at the bottom with the green plus Create Virtual Device...

New virtual device

In Category, select Phone, it seems to be the default there, for example emulator we will create in the image and likeness of Galaxy Nexus, click Next

Android Studio , based on the images installed on my system, Marshmallow version 6.0 was recommended to me,

since I haven’t downloaded Android N 7.0, however, this is enough for tests

on the third tab Other Images, you can select a different version, you can experiment if you want) click Next

In the next step you can rename our virtual device , change screen size, android version,

although you can leave it that way.

Of greater interest is the button additional settings Show Advanced Settings

by clicking on which the camera and network settings elements will be shown, you can adjust the volume random access memory, the size of the SD CARD is especially important regarding memory, I left 1 GB, you can put 512 MB if the RAM on your PC is not enough.

Click Finish, after some thought when creating a new one AVD , you will see something new in the manager virtual device .

In the right corner there are three buttons: a green arrow - start the emulator, a green pencil - change device properties, and a black down arrow opens an additional drop-down menu where you can clean, clone and delete the device.

Since we are writing for Android, to run applications we will need a smartphone running it, but, of course, there is an emulator and you have already downloaded it along with Android Studio. True, it does not work right out of the box and you will have to configure it a little. In this article we will do just that.

Virtual Android devices

Virtual Android devices are necessary for testing applications without installing them on real devices; for short they are called AVD (from English Android Virtual Device). They can be configured to emulate various hardware characteristics such as different sizes screen, memory capacity, presence or absence of cameras, support GPS navigation or accelerometer. At standard installation Android Studio installs a set of default device templates, mainly Nexus phones, which allow you to create your own AVDs based on them. You can also download additional templates or create your own to match any Android device in terms of processor type, memory size, pixel density and screen size.

When launched, the AVD appears as a window emulating the device. For example, photo below.

Creating an AVD

New AVDs are created and managed in Android Virtual Device Manager, which can be worked with both in the command line and in a convenient graphical interface. You can launch the manager from Android Studio by selecting the menu option Tools -> Android -> AVD Manager. In this article, we will not consider working through the command line.

After launching AVD Manager, click the "Create a virtual device" button, the virtual device configuration window will appear.


For example, let's create a Nexus S emulator. We choose it because it has a fairly small screen, which means that when the virtual device starts, the processor will be less loaded. We don't need it at all big screen for Hello World, later you, of course, can create your own instance and work with configurations that are closer to reality.

As you can see, there are several tabs for different categories of devices, we need a second one called Phone. On it, select the first line, Nexus S, click Next and wait for the installation to complete. After this, the settings window will appear:


Here you can set the name and various settings. Let's not touch anything and just click Finish. This completes the creation of the new AVD.

Launching the AVD

To launch the emulator, simply click on the green triangle opposite its name on the main page of AVD Manager. The launch, especially the first one, takes quite a long time. To speed up subsequent startups, uncheck "Use Host GPU" and check "Store a snapshot for faster startup".

Snapshot is something like a snapshot of the emulator state, which is loaded when the virtual device starts and allows you to reduce startup time to a few seconds. You can enable this feature only if you disable the "Use Host GPU" option.

Also, to speed up development, you can not turn off the emulator when working in Android Studio, so that every time you launch the application there is no need to wait for it to launch; the studio will understand that it needs to be launched already in a running emulator.

Conclusion

Now we have everything we need to write our first Android application. In the next article we will launch it.







2024 gtavrl.ru.