Implementing for Android
Development for the plugin is nearly complete. All that’s left is the Android implementation!
Register the plugin with Capacitor
Prerequisite: Familiarize yourself with the Capacitor Custom Native Android Code documentation before continuing.
Open up the Capacitor application’s Android project in Android Studio by running npx cap open android. Expand the app module and the java folder and right-click on your app’s Java package (the io.ionic.cap.plugin package).
Select New -> Package from the context menu and create a subpackage named plugins. Right-click the plugins package and repeat the preceding process to create a subpackage named ScreenOrientation.
Next, right-click the ScreenOrientation package and add a new Java file by selecting New -> Java File from the context menu. Name this file ScreenOrientationPlugin.java. Repeat the process to create a new file named ScreenOrientation.java.
Copy the following code into ScreenOrientationPlugin.java:
package io.ionic.cap.plugin.plugins.ScreenOrientation;
import com.getcapacitor.Plugin;
import com.getcapacitor.PluginCall;
import com.getcapacitor.PluginMethod;
import com.getcapacitor.annotation.CapacitorPlugin;
@CapacitorPlugin(name = "ScreenOrientation")
public class ScreenOrientationPlugin extends Plugin {
@PluginMethod()
public void orientation(PluginCall call) {
call.resolve();
}
@PluginMethod()
public void lock(PluginCall call) {
call.resolve();
}
@PluginMethod()
public void unlock(PluginCall call) {
call.resolve();
}
}
Register the plugin class within the project’s MainActivity to bridge between Java and JavaScript. Open MainActivity.java and add an onCreate() method where we can register the plugin:
package io.ionic.cap.plugin;
import android.os.Bundle;
import com.getcapacitor.BridgeActivity;
import io.ionic.cap.plugin.plugins.ScreenOrientation.ScreenOrientationPlugin;
public class MainActivity extends BridgeActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
registerPlugin(ScreenOrientationPlugin.class);
super.onCreate(savedInstanceState);
}
}