## Android Platform Guide
The following guide will assist you in setting up your development environment for building Cordova apps on Android devices. It also provides the option to integrate Android-specific command-line tools into your development workflow. Before proceeding with the setup, it is important to note that you will need to install and configure the necessary requirements regardless of whether you intend to utilize Android-specific command-line tools or Coro
_D_ \- D \- DvaVvavvaVvaVvaVvaVvaVvaVvaVvaVvaVvbvvbvvvvvvvvvvvvvvvvvvvvvvvvbvvvvvvvvvvvvvvvvvvvvvvvbvvvvvvvbvvvvvbvvvvvvvbvvvvvbvvvvvbvvvvvbvvvbvbvvvvvbvvvbvvvbvvvb
### Android API Level Support
The supported Android API Levels (versions of Android) correspond with the Cordova-Android released versions are listed in the table below:
| cordova-android Version | Android API-Levels (Android Version) | Library & Tooling Version |
|----------------|------------------------------------|------------------------------------|
| 12.0.x | 24 (7.0) - 33 (13.0) | Build Tools: ^33.0.2 |
| | | Kotlin: 1.7.21 |
| | | Gradle: 7.6 |
| | | Android Gradle Plugin: 7.4.2 |
| | | AndroidX Compat Library: 1.6.1 |
| | | AndroidX WebKit Library: 1.6.0 |
| | | AndroidX Core SplashScreen: 1.0.0 |
| | | Google Services Gradle Plugin: 4.3.15 |
| 11.0.x | 22 (5.1) - 32 (12L) | Build Tools: ^32.0.0 |
| | | Kotlin: 1.7.21 |
In summary, the latest version of cordova-android that supports both Android API Levels is version 12.0.x, which requires Build Tools version **33.0.2** and uses libraries and tools such as **Kotlin** version **1.7.21**, **Gradle** version **7.6**, **Android Gradle Plugin** version **7.4.2**, and **AndroidX Compat Library** version **1.6.1**, among others. For older versions (e.g., API Levels 5 through 10), please consult the respective documentation for guidance on installing the appropriate software and libraries for your development needs.
以下是重构后的内容:
### Gradle版本
- **7.4.2**
- Android Gradle插件版本: **7.2.1**
- AndroidX Compat库版本: **1.4.2**
- AndroidX WebKit库版本: **1.4.0**
- AndroidX Core SplashScreen版本: **1.0.0-rc01**
- Google Services Gradle插件版本: **4.3.10**
### 支持的Android系统和构建工具版本
- **10.1.x**
- 支持的Android系统版本范围: **22 (5.1) - 30 (11.0)**
- 构建工具版本: **Build Tools: ^30.0.3**
- Kotlin版本: **1.5.21**
- **9.X.X**、**8.X.X**、**7.X.X**、**6.X.X**、**5.X.X**、**4.1.X** 和 **4.0.X**
- 支持的Android系统版本范围: **根据实际情况填写`19 (4.4) - 28 (9.0)`、`19 (4.4) - 27 (8.1)`、`19 (4.4) - 26 (8.0)`、`16 (4.1) - 26 (8.0)`、`14 (4.0) - 23 (6.0)`、`14 (4.0) - 22 (5.1)`、`10 (2.3.3) - 22 (5.1)` 和 `10 (2.3.3) - 21 (5.0)`**
- 构建工具版本: **根据实际情况填写对应的构建工具版本,例如:`Build Tools: ^30.0.3`**
- Kotlin版本: **根据实际情况填写对应的Kotlin版本,例如:`Kotlin: 1.5.20`**
### Cordova CLI版本(注意:以上列出的cordova-android版本并非Cordova CLI版本)
```bash
cordova platform ls
```
Cordova generally stops supporting Android versions that fall below 5% on Google's distribution dashboard. If you're using an older version of Android, please refer to the following steps to ensure compatibility with Cordova-Android:
First, check your current version of Android by visiting the Google Distribution dashboard. Once you know your current version, compare it to the supported versions listed in the documentation. If your version is not supported, consider upgrading your device or switching to a newer version of Android.
Next, make sure you have the necessary system requirements for Cordova-Android. The Cordova-Android plugin relies on the Android SDK, which can be installed on macOS, Linux, or Windows operating systems. To verify your system meets the necessary requirements, refer to the "Install Android Studio" guide provided by Google. Additionally, you'll need to install Java Development Kit (JDK), cordova-android, and Gradle, as detailed in the following section.
System Requirements
Cordova-Android relies on the Android SDK, which can be installed on macOS, Linux, or Windows operating systems.
To ensure your system meets the necessary requirements, please refer to the "Install Android Studio" guide provided by Google.
The Required Software & Tools
Java Development Kit (JDK)
cordova-android
JAVA_HOMEcordova-androidCORDOVA_JAVA_HOMEJAVA_HOME
Gradle
As of Cordova-Android 6.4.0, Gradle is required to be installed. You can download and install Gradle from the official website (https://gradle.org/releases/) or follow the installation instructions in the "Install Gradle" guide provided by Google.
path
Note:
This is the system's Gradle version. The Gradle binary within the system will create the Gradle Wrapper file, which declares and obtains the appropriate version of Gradle required for building the Android application. While it is not necessary for the system-level and project-level Gradle versions to match, they should be compatible with each other. The specific version of Gradle used in the project is defined in the Cordova-Android package and is set based on what Android supports.
In order to build an Android application using Gradle, you need to have Android Studio installed. Download and install Android Studio from the official Android Developer website, and follow the instructions provided on that site to get started. When opening Android Studio for the first time, it will guide you through the process of installing the Android SDK packages.
It is recommended to install the latest version of the SDK Platform and SDK Tools based on the version of Cordova-Android already installed in your project. To determine which version of these tools is supported, refer to the Android API Level Support section. This information can help you ensure that you have the correct tools for building your Android application.
Cordova CLI requires specific environment variables to function correctly. These variables must be set before using the Cordova CLI. Below are the steps to set the environment variables:
1. Open your command prompt.
2. Navigate to the Android SDK ROOT directory.
3. Open the sdkmanager.cmd or terminal (depending on your operating system).
4. Type in the following commands and press Enter after each one:
* Tools > SDK Manager
* Install Android SDK Build-Tools
5. Once the installation is complete, open again your command prompt or terminal and type the following commands:
* Tools > SDK Manager
* Install SDK Command-line Tools (latest)
6. After that, type the following commands and press Enter after each one:
* Tools > SDK Manager
* Install Android SDK Platform-Tools
7. Next, type the following commands and press Enter after each one:
* Tools > SDK Manager
* Install Android Emulator
8. Finally, you need to set the environment variables by editing your bash profile or environment variables depending on your operating system. For macOS and Linux, open ~/.bash_profile and add the following lines:
* export JAVA_HOME=/path/to/your/java/home
* export ANDROID_HOME=/path/to/your/android/home
* export PATH=$JAVA_HOME/bin:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools:$PATH
9. Reload your terminal to see these changes reflected or run the following command to apply them immediately: source ~/.bash_profile (macOS and Linux) or setx ANDROID_HOME "/path/to/your/android/home" (Windows).
10. Now, you should be able to use the Cordova CLI without any issues.
These steps may vary depending on the installed version of Windows. To ensure that the changes take effect, it's recommended to close and reopen any command prompt windows after making the necessary modifications. Here is an overview of the steps involved in creating a new environment variable and setting your PATH:
1. Create a new environment variable:
Click on "New..." button.
Enter the appropriate name for the Variable in the "Variable name" field.
Type the desired value in the "Variable value" field.
Click on the "OK" button to create the new environment variable.
2. Set your PATH:
Select "PATH" from the list of already defined variables.
Click on the "Edit..." button to open the editing options for this variable.
Click on the "New" button to add a new path.
Type in the relevant location where you have installed the Android SDK (replace this with your local installation path). Repeat step 3 and 4 until all paths are added. Examples of paths include:
```bash
C:\Users\[your user]\AppData\Local\Android\Sdk\platform-tools
C:\Users\[your user]AppData\Local\Android\Sdk\cmdline-tools\latest\bin
C:\Users\[your user]\AppData\LocalAndroid\Sdk\build-tools
C:\Users\[your user]\AppData\Local\AndroidSdk\emulator
```
Once all paths have been added, click the "OK" button to save the changes and close any opened windows for setting and editing environment variables. This process should now successfully set up the required environment variables for using Android SDK tools in your system.
Project Configuration
Setting up an Emulator
If you wish to run your Cordova app on an Android emulator, you'll need to first create an Android Virtual Device (AVD). To configure it correctly, refer to the following Android documentation for more details:
Once your AVD is ready, you can deploy your Cordova application to the emulator by running the following command:
Configuring Gradle
Cordova-Android projects are built using Gradle. To configure the build process, you can set certain Gradle properties that Cordova exposes. The following properties are available:
You can set the following properties in one of four ways:
1. Exporting the property to your project's build script:
```bash
export ORG_GRADLE_PROJECT_cdvMinSdkVersion=20
cordova build android
```
2. Using Gradle arguments in your `cordova run` command:
```bash
cordova run android -- --gradleArg=-PcdvMinSdkVersion=20
```
3. Setting the property in your build.gradle file:
```groovy
cdvMinSdkVersion = 20
ext.cdvMinSdkVersion = 20
before_build
Extending build.gradle
build.gradlebuild-extras.gradlebuild.gradleapp
/platforms/android/appbefore_build
```
4. In your `build.gradle` file, you can configure the JVM arguments for Gradle:
```groovy
--jvmargs "-Xmx2048m" "-Xmx2097152k" "-Xmx2g"
```
The supported units are: `-Xmx2097152k`, `-Xmx2048m`, and `-Xmx2g`.
在您的Android项目中,您需要设置版本代码(Version Code)。请按照以下步骤操作:
1. 在`android-versionCodewidget`文件夹中创建一个名为`version`的文件。
2. 在`version`文件中输入如下内容:MAJOR.MINOR.PATCH,例如:1.0.0。
3. 转到`cdvBuildMultipleApks`目录,并执行以下命令:
```arduino
cdvBuildMultipleApks android-versionCode version
```
注意:有些插件可能会自动为您的项目设置此Gradle属性。
4. (可选)如果您需要签名应用,可以参考Android文档创建签名所需的文件。签名应用需要以下参数:
```yaml
--keystore --storePassword --alias --password --keystoreType --packageTypeapkbundle
buildrun
```
示例:
```arduino
cordova run android --release -- --keystore=../my-release-key.keystore --storePassword=password --alias=alias_name --password=password --packageType=bundle
```
5. 在项目的根目录下创建或编辑`build.json`文件。您可以在此处添加构建配置信息。示例:
```json
{
"android": {
"signingConfigs": [{
"storeFile": "path/to/your/keystore",
"storePassword": "your_keystore_password",
"keyAlias": "your_key_alias",
"keyPassword": "your_key_password"
}],
"buildTypes": {
"release": {
"minifyEnabled": false, // or true if you want to minify the code before signing it
"signingConfig": "your_signing_config"
}
}
}
}
```
其中 `signingConfig="your_signing_config"` 需要替换成您在第4步中定义的签名配置名称。
DebuggingThe debugging tools provided with the Android SDK are detailed in the Android developer documentation. In addition, this documentation also offers an introduction on how to debug web applications running in a WebView within your application.
# Opening a Project in Android Studio
Cordova-Android projects can be opened within Android Studio. This feature is especially useful if you want to take advantage of the built-in Android debugging and profiling tools or if you're developing Android plugins.
To open a Cordova-Android project in Android Studio:
```bash
platforms/android
```
Once it finishes importing, you should be able to build and run the app directly from Android Studio. For more information, please see [Upgrading cordova-android](https://cordova.apache.org/docs/en/latest/guide_platforms_www/plugin_lifecycle_guide.md#upgrading-cordova-android) and [Cordova and Android](https://cordova.apache.org/docs/en/latest/guide_platforms_www/index.md).
Native Android apps are typically structured around a series of activities, each representing an individual screen within the application. The user interacts with these activities to complete different tasks. Each activity has its own lifecycle, which is managed as it enters and exits the foreground on the user's device.
In comparison, Cordova applications for the Android platform are executed within a single Android activity that contains a WebView. This activity serves as the host for your app, and its lifecycle is exposed to your application through document events fired by the WebView. While these events may not exactly align with Android's lifecycle methods, they can still provide guidelines for saving and restoring your app's state.
Cordova's document events correspond to certain Android callbacks in the following way:
- devicereadyonCreate()
- pauseonPause()
- resumeonResume()
Android presents some unique challenges compared to most other Cordova platforms. Most other Cordova platforms have a similar concept of lifecycles and should fire the same events when similar actions happen on a user's device. However, Android's native Activity lifecycle can sometimes cause unexpected issues that need to be addressed differently than those found in Cordova platforms.
The primary difference between Android and other Cordova platforms is the way Android handles its native activity lifecycle. In Android, activities are created, resumed, and destroyed as part of the app's lifecycle. This means that if an event occurs outside of the scope of an activity, it may not be properly handled by Cordova, causing issues that need to be addressed manually. For example, if an error occurs while the app is running in the background, it may not be reported back to the app through the normal lifecycle channels, making it difficult to diagnose and resolve the issue.
To address these unique challenges associated with Android's lifecycle, developers must be aware of the differences between Android and other Cordova platforms. They must also be proactive in monitoring their app's behavior and handling any unexpected events that occur during runtime. By doing so, they can ensure that their app continues to run smoothly and provide a great user experience even in the face of unexpected issues.
In Android, it is possible for the operating system to terminate background activities in order to free up system resources when the device's memory is low. Unfortunately, this can result in the loss of your application's state when the activity responsible for holding your app is killed. This happens whenever the user navigates away from your application and returns later, as the OS will recreate both the Activity and the WebView that was part of your Cordova app. However, state preservation does not occur automatically for your Cordova app.
It is therefore essential for your app to be aware of the various lifecycle events that are fired during its operation, and to maintain whatever state is necessary to ensure that a user's context within your app remains intact even if they leave and return later. The exact circumstances under which this might happen will depend on the specific behavior of your application and the interactions of your users with it.
Your application is susceptible to being destroyed by the OS whenever it leaves the sight of the user. There are two main situations in which this can occur.
The first and most obvious case is when the user presses the home button or switches to another application. This happens because these actions typically result in a system shutdown or a change in focus, causing your application to be removed from memory.
To prevent this from happening, you must take steps to ensure that your app remains in the foreground at all times. One way to do this is by using the Android ActivityManager API, which provides methods for checking if an app is currently running and managing its lifecycle.
By using this API, you can implement logic that ensures your app remains active when the user is interacting with it. For example, you could use a service to keep the app running even when it is not visible on the screen, or you could use a broadcast receiver to receive notifications from other apps and respond appropriately.
Overall, it's important to understand that leaving the foreground can cause your application to be destroyed, so taking steps to keep it active is critical for maintaining its functionality and ensuring a smooth user experience.
Cordova applications, as mentioned before, are typically limited to a single activity that contains the WebView. This is because they rely heavily on web-based technologies and the WebView is the primary way in which these technologies are accessed from within the application. However, there is an important exception to this rule that can have significant implications for plugin developers and users of Cordova applications. This exception arises when other activities are launched by plugins and push the Cordova activity to the background.
These additional activities are typically designed to perform specific tasks using native applications that are installed on the device. For example, if you use a Cordova camera plugin, the plugin may launch whatever camera activity is natively available on the user's device in order to take a photo. By reusing the installed camera application in this way, your application can provide a more native experience when the user attempts to take a photo.
However, while this approach can improve the user experience, it also introduces a potential risk. If the native activity that is launched by the plugin pushes your Cordova activity to the background, there is a chance that the operating system will terminate it. This is because many modern operating systems prioritize the stability of their foreground applications and will often terminate any app that has been inactive for a certain amount of time to prevent memory leaks or other issues. To mitigate this risk, it is important for Cordova plugin developers to be mindful of how they interact with native activities and to design their plugins in a way that minimizes the likelihood of being backgrounded by another activity.
To gain a better understanding of this second scenario, let's consider an example involving the camera plugin. Suppose you have an application that requires users to take profile photos. The sequence of events in such an application when everything goes according to plan would look something like this:
1. The user is interacting with your app and needs to take a picture.
2. The camera plugin launches the native camera activity.
3. The Cordova activity is pushed to the background (a pause event is fired).
4. The user takes a photo.
5. The camera activity finishes.
6. The Cordova activity is moved to the foreground (a resume event is fired).
7. The user is returned to your application where they left off.
However, this sequence of events can be disrupted if a device is low on memory. If the Activity is killed by the OS, the above sequence of events will play out differently:
1. The user is interacting with your app and needs to take a picture.
2. The camera plugin launches the native camera activity (possibly without finishing).
3. The Cordova activity is pushed to the background (a pause event is fired).
4. Due to low memory, the OS kills the Activity without allowing it to complete its task or return control back to your app. This may happen even if the user has not taken any photos yet.
In both scenarios, the goal remains the same: capturing a photo for the user's profile. However, the way in which this process is handled can vary depending on factors such as device memory and system behavior.
When a user takes a photo using the Camera Plugin in Cordova, the OS destroys the Cordova activity. This is done to free up resources and avoid memory leaks. However, this also means that the application does not maintain its state as part of the lifecycle. When the user returns to the app, the Webview is recreated and the app appears to have restarted from scratch. This can be confusing for users who may not realize that they were simply taken back to the login screen.
To prevent this experience, it is important to subscribe to events and properly maintain state as part of the activity lifecycle. The key to preventing this is to respect the lifecycle and bind events accordingly. By doing this, you can ensure that the application maintains its state even when it is being destroyed and recreated by the OS.
在上述示例中,有一个额外的因素仅适用于第二种情况(即插件启动外部活动)。当用户完成拍照时,不仅应用程序的状态丢失了,用户拍摄的照片也丢失了。通常情况下,照片会通过已与相机插件注册的回调传递到您的应用程序。然而,当Webview被销毁时,该回调永远消失了。幸运的是,Cordova-
Android 5.1.0及更高版本提供了一种方法,可以在您的应用程序恢复时获取插件调用的结果。
当应用程序恢复时,可以使用以下代码来检索插件回调结果:
```java
@Override
protected void onResume() {
super.onResume();
PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, getImage());
pluginResult.setKeepCallback(false);
dispatcher.sendPluginResult(pluginResult);
}
private byte[] getImage() {
byte[] imageData = null;
try {
imageData = getPhotoFromGallery();
} catch (IOException e) {
Log.e(TAG, "Unable to retrieve photo from gallery", e);
} finally {
return imageData;
}
}
private byte[] getPhotoFromGallery() throws IOException {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File("path/to/photo");
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
getApplicationContext().sendBroadcast(mediaScanIntent);
// Wait for the scan to complete before retrieving the photo data
Thread.sleep(2000);
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(contentUri, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
String imagePath = cursor.getString(index);
cursor.close();
return imagePath.getBytes();
} else {
throw new RuntimeException("Failed to retrieve photo data");
}
}
```
在 Android 中,错误类型可以分为不同的类别。以下是常见的错误类型及其含义:
1. **No Result**:此错误表示请求未返回任何结果。
2. **Error**:通用错误消息,表示发生了意外的问题。
3. **Class not found**:找不到指定的类。
4. **Illegal access**:试图访问受保护的类、方法或字段。
5. **Instantiation error**:无法实例化指定的类。
6. **Malformed url**:URL 格式不正确,无法解析为有效的网络资源。
7. **IO error**:输入/输出操作发生错误,通常与文件读写或网络通信有关。
8. **Invalid action**:无效的操作或动作。
9. **JSON error**:处理 JSON 数据时发生了错误。
关于 `resultpluginStatus` 的示例代码如下所示:
```java
// 结果插件状态示例代码
String resultPluginStatus = "resumepauseresumeresumeevent.pendingResult";
```
对于 `Android Quirks`,在 Cordova-Android 平台中,默认的 API 级别已经升级了。在 Android 9 设备上,明文通信默认被禁用。可以通过在 `config.xml` 文件中设置 `android:usesCleartextTraffic` 属性来启用明文通信,例如:
```xml
...
...
```
以上是一个示例中的 `config.xml` 配置文件的内容,其中的 `android:usesCleartextTraffic="true"` 将启用明文通信。
如果需要查看更多关于 Android 清单信息的文档,请参考 Android 开发者文档。
最后,关于测试应用程序的 Activity 生命周期,你可以按照以下步骤进行:
1. 在 Android Studio 中打开你的项目。
2. 在活动(Activity)的源代码文件中,找到你想要测试的活动类。
3. 创建一个测试类,继承自 `org.junit.Test` 或者你选择的其他测试框架的相关类。
4. 在测试类中添加测试方法,使用断言或其他验证方法来验证活动的行为和功能是否符合预期。
5. 运行测试用例并查看测试结果,以确保应用程序的各个部分按照预期工作。
To test the destruction of activities in low memory situations, Android offers a developer setting. This setting, which can be accessed through the Developer Options menu on your device or emulator, allows you to simulate low memory scenarios. Enabling the "Don't keep activities" option ensures that your application is capable of properly maintaining its state even when resources become scarce. However, it is important to conduct thorough testing with this setting enabled to verify the effectiveness of your application's handling of low memory situations. By doing so, you can ensure that your app remains resilient and performs well under challenging conditions.