- Capacitor Android Documentation
- Android Support
- Adding the Android Platform
- Opening the Android Project
- Running Your App
- Running on the Command-Line
- Running with Android Studio
- Troubleshooting
- Next Steps
- Further Reading
- Android Development
- Android Studio
- Installing Android Studio
- Installing the Android SDK
- Configuring Command Line Tools
- Creating an Android Virtual Device
- Set up an Android Device
- Cordova Setup
- Gradle
- Project Setup
- Running with Capacitor
- Live reload
- Running with Cordova
- Debugging Android Apps
- Using Chrome DevTools
- Viewing Native Logs
- Capacitor Android Plugin Guide
- Getting Started
- Using Kotlin
- Plugin Basics
- Simple Example
- Accessing Called Data
- Returning Data Back
- Persisting a Plugin Call
- Running Code on Plugin Load
- Permissions
- Annotation Changes
- Implementing Permission Requests
- Permission Callback
- Initiating a Permission Request
- Manifest
- Error Handling
- Unavailable
- Unimplemented
- Presenting Native Screens
- Intents without Result(s)
- Intents with Result(s)
- Plugin Events
- Override navigation
Capacitor Android Documentation
Capacitor features a native Android runtime that enables developers to communicate between JavaScript and Native Java or Kotlin code.
Capacitor Android apps are configured and managed through Android Studio.
Android Support
API 21+ (Android 5 or later) is supported, which represents over 95% of the Android market . Capacitor requires an Android WebView with Chrome version 60 or later. On Android 5 and 6, Capacitor uses the Android System WebView . On Android 7+, Google Chrome is used.
Adding the Android Platform
First, install the @capacitor/android package.
Then, add the Android platform.
Opening the Android Project
To open the project in Android Studio, run:
Alternatively, you can open Android Studio and import the android/ directory as an Android Studio project.
Running Your App
You can either run your app on the command-line or with Android Studio.
To use an Android Emulator you must use an API 24+ system image. The System WebView does not automatically update on emulators. Physical devices should work as low as API 21 as long as their System WebView is updated.
Running on the Command-Line
To run the project on a device or emulator, run:
The command will prompt you to select a target. Learn more about run .
Running with Android Studio
In Android Studio, first select the device or emulator and then click the run or debug button to run your app. Unless you’re debugging Java or Kotlin code, the run button is preferred.
Troubleshooting
If you encountered any issues while getting started, you can consult the Android Troubleshooting Guide . Feel free to open a discussion if you need help.
Next Steps
If your app ran you are now ready to continue developing and building your app. Use the various APIs available, Capacitor or Cordova plugins, or custom native code to build out the rest of your app.
Further Reading
Follow these Android-specific guides for more information on setting permissions for your app, updating dependencies, building plugins, and more:
Источник
Android Development
This guide covers how to run and debug Ionic apps on Android emulators and devices using Capacitor or Cordova . Android apps can be developed on Windows, macOS, and Linux.
Android Studio
Android Studio is the IDE for creating native Android apps. It includes the Android SDK , which will need to be configured for use in the command line.
Android Studio is also used to create Android virtual devices , which are required for the Android emulator. Ionic apps can also be launched to a device .
We don’t recommend using Android Studio for developing Ionic apps. Instead, it should only really be used to build and run your apps for the native Android platform and to manage the Android SDK and virtual devices.
Installing Android Studio
Download Android Studio from the Android website . More detailed installation instructions can be found in the User Guide .
Installing the Android SDK
Once installed, open Android Studio. The IDE should detect that the Android SDK needs to be installed. In the SDK Components Setup screen, finish installing the SDK. Keep note of the Android SDK Location .
By default, the latest stable SDK Platform is installed, which includes a collection of packages required to target that version of Android.
To install system images and other minor SDK platform packages, you may need to ensure Show Package Details is checked at the bottom of the SDK Manager.
For future reference, the Android SDK can be managed with Android Studio in the Configure » SDK Manager menu of the Android Studio welcome screen or Tools » SDK Manager inside Android projects.
Configuring Command Line Tools
The Android SDK ships with useful command-line tools . Before they can be used, some environment variables must be set. The following instructions are for macOS and Linux. For Windows, check the documentation on setting and persisting environment variables in terminal sessions.
/.bash_profile , or similar shell startup scripts, make the following modifications:
Set the ANDROID_SDK_ROOT environment variable. This path should be the Android SDK Location used in the previous section.
Add the Android SDK command-line directories to PATH . Each directory corresponds to the category of command-line tool .
# avdmanager, sdkmanager export PATH=$PATH:$ANDROID_SDK_ROOT/tools/bin
# adb, logcat export PATH=$PATH:$ANDROID_SDK_ROOT/platform-tools
# emulator export PATH=$PATH:$ANDROID_SDK_ROOT/emulator
For apksigner and zipalign , $ANDROID_SDK_ROOT/build-tools must also be added to PATH .
Creating an Android Virtual Device
Android Virtual Devices (AVDs) are blueprints that the Android emulator uses to run the Android OS. The following documentation is a quick way to get the Android emulator set up. For more detailed instructions and information, see the Android documentation .
AVDs are managed with the AVD Manager. In the Android Studio welcome screen, click Configure » AVD Manager . The AVD Manager can also be opened inside Android projects in the Tools » AVD Manager menu.
Click Create Virtual Device and select a suitable device definition. If unsure, choose Pixel 2 . Then, select a suitable system image. If unsure, choose Pie (API 28) with Google Play services. See Android version history for information on Android versions.
Once the AVD is created, launch the AVD into the Android emulator. Keeping the emulator running is the best way to ensure detection while developing Ionic apps for Android.
Set up an Android Device
Actual Android hardware can also be used for Ionic app development. But first, the device must be set up for development. The following documentation is a quick way to set up Android devices for development. For more detailed instructions and information, see the Android documentation .
- Enable USB debugging on the device. Open Settings , navigate to Developer options , and enable USB debugging . The Developer options menu may need to be enabled first. See the Android documentation for instructions.
- Ensure the device has permission to connect to the computer. For macOS, no additional setup is required. For Windows, install the OEM USB drivers .
Verify the connection works by connecting the device to the computer with a USB cable and using the following command:
The device should be listed. See the full adb documentation for troubleshooting and detailed information.
Cordova Setup
Additional setup is required for Cordova to support programmatic builds. This section is not necessary for Capacitor.
Native Android apps are compiled with the Java programming language. Download JDK8 from the download page .
Unfortunately, Cordova is not compatible with the latest version of Java.
Gradle
Gradle is the build tool used in Android apps and must be installed separately. See the install page for details.
Project Setup
Before apps can be deployed to Android simulators and devices, the native project must be configured.
Generate the native project, if it does not already exist.
For Capacitor, run the following:
For Cordova, run the following:
For Capacitor, open the capacitor.config.json file and modify the appId property.
For Cordova, open the config.xml file and modify the id attribute of the root element, . See the Cordova documentation for more information.
Running with Capacitor
Capacitor uses Android Studio to build and run apps to simulators and devices.
Develop the Ionic app and sync it to the native project.
With each meaningful change, Ionic apps must be built into web assets before the change can appear on Android simulators and devices. The web assets then must be copied into the native project. Luckily, this process is made easy with a single Ionic CLI command.
In Android Studio, click the Run button and then select the target simulator or device.
Live reload
To start a live-reload server run the following command.
When running on a device make sure the device and your development machine are connected to the same network.
Running with Cordova
The Ionic CLI can build, copy, and deploy Ionic apps to Android simulators and devices with a single command. It can also spin up a development server, like the one used in ionic serve , to provide live-reload functionality.
Run the following to start a long-running CLI process that boots up a live-reload server:
Now, when changes are made to the app’s source files, web assets are rebuilt and the changes are reflected on the simulator or device without having to deploy again.
Debugging Android Apps
Once an app is running on an Android device or emulator, it can be debugged with Chrome DevTools.
Using Chrome DevTools
Chrome has web developer tool support for Android simulators and devices. Go to chrome://inspect in Chrome while the simulator is running or a device is connected to the computer and Inspect the app that needs to be debugged.
Make sure your application is running on the device or simulator, or it will not show up in the list.
Viewing Native Logs
If running with Android Studio, native logs can be found in Logcat .
If the Logcat window is hidden, you can enable it in View » Tool Windows » Logcat .
You can also access Logcat with ADB .
Источник
Capacitor Android Plugin Guide
Building Capacitor plugins for Android involves writing Java or Kotlin to interface with Android SDKs.
Getting Started
To get started, first generate a plugin as shown in the Getting Started section of the Plugin guide.
Next, open echo/android/ in Android Studio. You then want to navigate to the .java file for your plugin, which changes depending on the Plugin ID and Plugin Class Name you used when creating the plugin.
For example, for a plugin with the ID com.domain.echo and the Plugin Class Name Echo , you would find the .java file at android/src/main/java/com/domain/echo/EchoPlugin.java .
Using Kotlin
Capacitor uses Java by default but you can use Kotlin instead, if you prefer.
After generating a plugin, right click the Java plugin class in Android Studio and select the “Convert Java file to Kotlin file” option from the menu. Android Studio will walk you through configuring the project for Kotlin support. Once this is completed, right click the Java class again and re-select the conversion option to convert it to a Kotlin class.
Plugin Basics
A Capacitor plugin for Android is a simple Java class that extends com.getcapacitor.Plugin and has a @CapacitorPlugin() annotation. It has some methods with @PluginMethod() annotation that will be callable from JavaScript.
Once your plugin is generated, you can start editing it by opening the file with the Plugin class name you choose on the generator.
Simple Example
In the generated example, there is a simple echo plugin with an echo function that simply returns a value that it was given.
This example demonstrates a couple core components of Capacitor plugins: receiving data from a Plugin Call, and returning data back to the caller.
Accessing Called Data
Each plugin method receives an instance of com.getcapacitor.PluginCall containing all the information of the plugin method invocation from the client.
A client can send any data that can be JSON serialized, such as numbers, text, booleans, objects, and arrays. This data is accessible on the getData field of the call instance, or by using convenience methods such as getString or getObject .
For example, here is how you’d get data passed to your method:
Notice the various ways data can be accessed on the PluginCall instance, including how to check for a key using getData ‘s has method.
Returning Data Back
A plugin call can either succeed or fail. Plugin calls borrow method names from JavaScript promises: call resolve() to indicate success (optionally returning data) and use reject() to indicate failure with an error message.
The resolve() method of PluginCall takes a JSObject and supports JSON-serializable data types. Here’s an example of returning data back to the client:
To fail, or reject a call, use call.reject , passing an error string and optionally an error code and Exception instance
Persisting a Plugin Call
In most cases, a plugin method will get invoked to perform a task and can finish immediately. But there are situations where you will need to keep the plugin call available so it can be accessed later. You might want to do this to periodically return data such as streaming live geolocation data, or to perform an asynchronous task.
See this guide on saving plugin calls for more details on how to persist plugin calls.
Running Code on Plugin Load
Occasionally, plugins may need to run some code when the plugin is first loaded.
To do this, provide an implementation for the load() method:
Permissions
If your plugin has functionality on Android that requires permissions from the end user, then you will need to implement the permissions pattern.
Before following this section, make sure you’ve set up your permission aliases and status interfaces. If you haven’t, see the Permissions section in the Web guide .
Annotation Changes
Still using @NativePlugin ? See the upgrade guide to switch to @CapacitorPlugin .
Add the permissions attribute in the @CapacitorPlugin annotation, which is an array of one or more @Permission annotations. Each @Permission annotation contains zero or more Android permission strings and a short alias describing the purpose.
Group permission strings in each @Permission by the distinct pieces of functionality of your plugin.If your plugin requires permissions in other platforms but not Android, then define the permission with the same alias but an empty array for strings . This causes the result of the permission request to automatically return as ‘granted’ for that permission alias.
Implementing Permission Requests
By defining permissions in your @CapacitorPlugin annotation, the checkPermissions() and requestPermissions() methods should be fully functional. App developers will be able to manually request permissions as needed. However, it is considered best practice to wrap plugin functionality with automatic permission requests as well.
Permission Callback
Create a void method with a single PluginCall parameter and annotate it with @PermissionCallback , then pass the name of the method as a string in the permission request call. The callback will run after the completion of the permission request.
Initiating a Permission Request
Permission requests are initiated by calling one of the request helper methods.
For a single alias requestPermissionForAlias may be used. Multiple aliases can be provided to requestPermissionForAliases . Use requestAllPermissions to request all permissions defined in the plugin annotation.
Manifest
Place any required install-time permissions in the AndroidManifest.xml of the plugin. Do not add runtime permissions (permissions that prompts users to accept). These should be added to the manifest of a Capacitor app by the app developer. Make sure your plugin documents any required runtime permissions that should be added in the app.
Error Handling
Unavailable
This error can be thrown to indicate that the functionality can’t be used right now, usually because it requires a newer Android API version.
It is recommended to gracefully degrade the experience with older APIs as much as possible. Use unavailable sparingly.
Unimplemented
Use this error to indicate that a method can’t be implemented for Android.
Presenting Native Screens
To present a Native Screen over the Capacitor screen we will use Android’s Intents . Intents allow you to start an activity from your app, or from another app. See Common Intents
Intents without Result(s)
Most times you just want to present the native Activity, in this case you can just trigger the relevant action .
Intents with Result(s)
Sometimes when you launch an Intent, you expect some result back. In that case you want to use startActivityForResult .
Create a callback method to handle the result of the launched activity with a PluginCall and ActivityResult parameter, and annotate it with @ActivityCallback . Pass the name of this method to startActivityForResult and it will run when the started activity is finished.
Plugin Events
Plugins can emit their own events that you can listen by attaching a listener to the plugin object like this:
To emit the event from the Java plugin class:
To remove a listener from the plugin object:
It is also possible to trigger global events on window . See the docs for triggerJSEvent .
Override navigation
Capacitor plugins can override the webview navigation. For that the plugin can override public Boolean shouldOverrideLoad(Uri url) method. Returning true causes the WebView to abort loading the URL. Returning false causes the WebView to continue loading the URL. Returning null will defer to the default Capacitor policy.
Источник