Ionic 3 Project Combat------Custom Plug-in _hybrid

Source: Internet
Author: User
Tags configuration settings export class

Before the Ionic 3 project plug-in structure has done a simple introduction Ionic 3 Plug-in applications: Plugin basic knowledge to understand

A plug-in should contain at least the following file:

Plugin-name

-----------------src//plugin support platform

------Android.java//Added support for Android platform

-----------------www//js file to expose the Cordova.exec method to the HTML/JS call

------Android.js

-----------------Plugin.xml//plug-in configuration file that informs the CLI which platform should copy which files from where, and what special settings the CLI should add to the platform when generating Config.xml

In custom Plug-ins, we can follow the above directory structure, build their own files, but this is more cumbersome, so generally do not recommend this.

It is recommended to use the plugin generation tool Plugman, he will automatically help us create the desired plug-in directory, and then to the corresponding file to achieve the functions we need.

1. Installation Plugman

$ NPM install-g Plugman
2. Create plug-in Template

Let's take a look at the Plugman available commands

Plugman manages plugin.xml-compatible Cordova plugins into cordova-generated projects. Usage ===== to display this Help file, with one of the following: $ Plugman--help $ plugman-h to display the Plugman V Ersion, use one of the following: $ Plugman--version $ plugman-v Optional flags----------------Debug|-d:ver Bose mode Install a plugin----------------$ plugman Install--platform <platform>--project <directory&gt ; --plugin <plugin> [--variable name=value] Parameters:-Platform <platform>: One of Android, iOS, Blackberr Y10, WP8, or Windows8-project <directory>: Path reference to a cordova-generated project of the platform spec  Ify-plugin <plugin&gt: One of the path reference to a local copy of a plugin, or a sqlremote https:or git:url pointing to a Cordova plugin (optionally append #branch: subdir) or a plugin ID from http://plugins.cordova.io-variable name=va Lue:some plugins require install-time variables to be Defined.

 These could are things like APIs keys/tokens or other app-specific variables. Optional parameters:-www <directory&gt: www assets for the plugin'll be installed to this directory. Install into the standard WWW directory for the platform Specified-plugins_dir <directory>: a copy Of the plugin is stored in this directory. The install into the <project directory>/plugins Folder-searchpath <directory&gt.: When looking up P
   Lugins by ID, look in this directory and each of their subdirectories for the plugin before hitting the registry.  Multiple search paths can be used by either specifying the flag, or by multiple separating with a paths (: On ' Nix,;

On Windows). Uninstall a plugin------------------$ plugman Uninstall--platform <platform>--project <directory>--p  Lugin <plugin-id> Parameters:-Platform <platform>: One of Android, iOS, Blackberry10, WP8, or WINDOWS8- PRoject <directory&gt: Path reference to a cordova-generated project's platform you Specify-plugin <plugin-i D&gt: The plugin to remove, identified by its ID ("The plugin.xml ' <plugin id> attribute) interacting with th E Registry ============================= notice:the Cordova Plugin Registry became read-only, so following  have been deprecated and removed: $ plugman adduser $ plugman Publish $ Plugman unpublish $ plugman Owner ADD/RM for managing plugins for the NPM registry, use corresponding NPM commands.
For more info on NPM commands "NPM help <command>". Learn about publishing your plugins to NPM in http://plugins.cordova.io/npm/developers.html Search for a plugin---- 

    ---------------$ plugman Search <keyword1 keyword2 ...> Display plugin Information-------------------------- $ plugman Info <pluginID> Manage Registry configuration-----------------------------Display current ConfiguRation settings: $ plugman config ls Display the current registry URL: $ plugman config get registry Set Regis Try URL: $ plugman Config Set Registry <url> Example: $ plugman Config Set Registry http://localhost:5984 /registry/_design/app/_rewrite Manage Owners-------------Plugin Owners are allowed to publish updates to a Plugin. To display a list of owners for a plugin, use: $ plugman owner ls <pluginID> Example: $ plugman owner ls Org.apache.cordova.core.file Create A Plugin---------------$ plugman Create--name <pluginName>--plugin_id <pluginID>--plugin_version <version> [--path <directory>] [--variable Name=value] Parameters:-< Pluginname&gt: The name of the plugin-<pluginid>: An ID for the plugin, Ex:org.bar.foo-<version>: A ve Rsion for the plugin, ex:0.0.1-<directory>: a absolute or relative path for the directory where the plugin proj ECT would be Created-variaBLE Name=value:extra variables such as description or Author Add a Package.json file to plugin-------------------------

 --------creates a Package.json file in the plugin based on values from Plugin.xml. $ plugman Createpackagejson <directory> Add a Platform to a Plugin--------------------------$ plugman PLATF ORM Add--platform_name <platform> Parameters:-<platform>: One of Android, iOS Remove a platform from a P Lugin-------------------------------$ plugman Platform Remove--platform_name <platform> Parameters:-<
 Platform&gt: One of Android, iOS


Then use the command to create the plug-in

Create A Plugin
---------------

    $ plugman Create--name <pluginName>--plugin_id <pluginID>-- Plugin_version <version> [--path <directory>] [--variable Name=value]

Parameters:

 -< Pluginname>:
 The name of the plugin-<pluginid>: An ID for the plugin, Ex:org.bar.foo
 -<version> : A version for the plugin, ex:0.0.1
 -<directory>: an absolute or relative path for the directory where the PL Ugin project would be created
 -variable Name=value:extra variables such as description or Author
The corresponding arguments are described, no translation is done here, and a plug-in template is created (the plug-in can optionally be created in any directory)
$ plugman Create--name zkcustomplugin--plugin_id zhaikun68.plugin.custom--plugin_version 0.0.1--path E:\zhaikun\ Myplugins--variable zhaikun68
To open a plug-in module that you created


3, add the platform supported by Plug-ins

Go to the root directory of the plug-in

Support Android

$ Plugman Platform Add--platform_name Android

Support iOS Platform

$ Plugman Platform Add--platform_name iOS

Plugin.xml File Content Description

<?xml version= ' 1.0 ' encoding= ' utf-8 '?> <!--plug-in logo, that is, the ID of the post installation to plugin, in the creation of Plug-ins is set--> <plugin " Zhaikun68.plugin.custom "version=" 0.0.1 "xmlns=" http://apache.org/cordova/ns/plugins/1.0 "xmlns:android=" http://s Chemas.android.com/apk/res/android "> <!--plug-in name--> <name>ZKCustomPlugin</name> <zhaikun 68/> <!--corresponding to our JavaScript file, the SRC attribute points to www/zkcustomplugin.js--> <js-module name= "Zkcustomplugin" src= "W Ww/zkcustomplugin.js "> <!--Specify clobbers, and then call zkcustomplugin.js through the value of target, which corresponds to the exports object in Zkcustomplugin.js- -> <clobbers target= "Cordova.plugins.ZKCustomPlugin"/> </js-module> <!--supported platforms android--&
    Gt <platform name= "Android" > <config-file parent= "*" target= "Res/xml/config.xml" &GT;&L t;! --This is to insert the following line of code in the Res/xml/config.xml file--> <feature name= "Zkcustomplugin" > <param na
       Me= "Android-package"                The value= "Zhaikun68.plugin.custom.ZKCustomPlugin"/><!--invoke the plug-in's class name, implementing the Execute method--> </feat ure> </config-file> <config-file parent= "/*" target= "Androidmanifest.xml"/><!--to ANDROIDM Anifest.xml files are modified--> <!--means to copy zkcustomplugin.java files from the plugin src/android directory to Android src/zhaikun68/plugin/ Custom directory to--> <!--If there is a reference package, it can also be copied to the Android under the designated Lib to--> <source-file src= "Src/android/zkcustomplugin. Java "target-dir=" Src/zhaikun68/plugin/custom/zkcustomplugin "/> </platform> <!--supported platforms ios--> &L T;platform name= "ios" > <config-file parent= "*" target= "config.xml" > <feature name= "zkcust
        Omplugin "> <param name=" ios-package "value=" Zkcustomplugin "/> </feature> </config-file> <source-file src= "src/ios/zkcustomplugin.m"/> </platform> </plugin>
Zkcustomplugin.js File Content Description
var exec = require (' cordova/exec ');

Exports.coolmethod = function (arg0, success, error) {

    /**
     * cordova.exec () method Description
     * Function (winparam) {} : Successful callback function. Assuming that your exec completes successfully, this feature will execute the
     * Function (Error) {}: Error callback function along with any parameters that you pass to it. If the operation did not complete successfully, this feature will perform an optional error parameter
     * "Service": the service name that is called on the native side, consistent with the original class name
     * "Action": the name of the action invoked on the native side, corresponding to the native class execute (), The native code is judged by the action to know what kind of functionality JS lets the native end perform
     * [arguments]: An array of parameters to the native environment
    /EXEC (Success, error, " Zkcustomplugin "," Coolmethod ", [arg0]);

Zkcustomplugin.java File Content Description
Package zhaikun68.plugin.custom;
Import Org.apache.cordova.CordovaPlugin;

Import Org.apache.cordova.CallbackContext;
Import Org.json.JSONArray;
Import org.json.JSONException;

Import Org.json.JSONObject;
 /** * This class echoes a string called from JavaScript. * * public class Zkcustomplugin extends Cordovaplugin {//must inherit cordovaplugin/** * Action corresponds to EXEC's action * args corresponding to exec passed parameter array * Callbackcontext: corresponding to the callback function called EXEC/@Override public boolean execute (String action, Jsonarr Ay args, Callbackcontext callbackcontext) throws Jsonexception {if (Action.equals ("Coolmethod")) {St
            Ring message = args.getstring (0);
            This.coolmethod (message, callbackcontext);
        return true;
    return false; } private void Coolmethod (String message, Callbackcontext callbackcontext) {if (message!= null && m Essage.length () > 0) {callbackcontext.success (message);//successful callback function} else {
            Callbackcontext.error ("expected one non-empty string argument.");
 /Failed callback function}}}

4. Add custom Plug-ins to the project we created

$ ionic Cordova Plugin Add E:\zhaikun\MyPlugins\ZKCustomPlugin
No success added, error message prompt
$ > Cordova plugin add E:\zhaikun\MyPlugins\ZKCustomPlugin--save
xrunning
command-failed! [ERROR] An error occurred while running Cordova plugin add E:\zhaikun\MyPlugins\ZKCustomPlugin--save (exit code 1):


        error:in Valid plugin! E:\zhaikun\MyPlugins\ZKCustomPlugin needs a valid Package.json
Error message translation probably is: The plug-in root directory requires a Package.json file

Daniel, who has a good memory, should have found the command to create a Package.json file in the Plugman tool

Add a Package.json file to plugin
---------------------------------
creates a Package.json file in the plugin base D on the values from Plugin.xml.

 $ Plugman Createpackagejson <directory>

Create a Package.json file (go to the root of the plug-in)

$ Plugman Createpackagejson E:\zhaikun\MyPlugins\ZKCustomPlugin
Enter the plug-in name, version number, plug-in description, Git warehouse address, author and certificate information, if not modified, always return to


Back to the root of our project, add plugins again

$ ionic Cordova Plugin Add E:\zhaikun\MyPlugins\ZKCustomPlugin

5. Plug-in Call

Add two buttons to the home.html file

<ion-header>
  <ion-navbar>
    <ion-title>Home</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  </p>
  <p>
    Take A look in the <code>src/pages/</code> directory to add or change tabs,< C12/>update any existing page or create new pages.
  </p>

  <!--Here are the two buttons added-->
  <button Ion-button (click) = "getnativesuccess ()" > Simulation-successfully invoke native plugins </button>
  <button Ion-button (click) = "getnativefailed ()" > Impersonation-failed invoke native plugin </button>

</ Ion-content>
Then modify the contents of the Home.ts file
Import {Component} from ' @angular/core ';
Import {Navcontroller} from ' Ionic-angular ';

Declare let cordova:any;//here is the modified code

@Component ({
  selector: ' Page-home ',
  templateurl: ' home.html '
})
Export Class Homepage {

  constructor (public navctrl:navcontroller) {

  }

  //Here is the modified code
  Getnativesuccess () {
    Cordova.plugins.ZKCustomPlugin.coolMethod (
      ' native plug-in call succeeded ',
      successmsg => {
        alert (successmsg)
      }, failedmsg => {
        alert (failedmsg)
      }
    );

  Here is the modified code
  getnativefailed () {
    Cordova.plugins.ZKCustomPlugin.coolMethod (
      ",
      successmsg = > {
        alert (successmsg)
      }, failedmsg => {
        alert (failedmsg)
      }
    );
  }
You can then compile the project
$ ionic Cordova Build Android
Effect chart




The debugging here is done on the real machine, and the run-time exception occurs when the browser is debugged

In addition, once the plug-in is added to the project, if you need to upgrade the plugin later, you need to uninstall the original plugin before reinstalling

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.