Ionic2 custom cordova plug-in development and use (Android), ionic2cordova

Source: Internet
Author: User

Ionic2 custom cordova plug-in development and use (Android), ionic2cordova

How to Write a cordova for the ionic2 project? After searching, I suspect that all the articles are copied and not detailed. I had a hard time on my own for one afternoon and had a lot of pitfalls. So I would like to write this article and record it.

If you want to write a log plug-in, you can write the log in the sdcard of your mobile phone.

1. Install plugman

npm install -g plugman

2. creat a plug-in framework

Plugman creat -- name plug-in name -- plugin_id plug-in id -- plugin_version plug-in version number

For example:

Copy codeThe Code is as follows: plugman create -- name cordovaHeaLog -- plugin_id cordova-plugin-hea-log -- plugin_version 1.0

Press enter to generate a project with such a structure

3. Added support for the Android platform

plugman platform add --platform_name android

We can see that an android folder and a java file are added under src.

4. Implement the log function

In src/android, I added a logUtil. java file.

The content is as follows:

Package cordova. plugin. hea. log; import android. OS. environment; import java. io. bufferedWriter; import java. io. file; import java. io. fileWriter; import java. io. IOException; import java. text. simpleDateFormat; import java. util. calendar; import java. util. date; public class logUtil {private static int SDCARD_LOG_FILE_SAVE_DAYS = 180; // The maximum number of days for storing log files in the SD card private static String LOG_PATH_SDCARD_DIR = Environment. getExt ErnalStorageDirectory (). toString () + "/VP2./log /"; // path of the log file in sdcard // log output format private static SimpleDateFormat LogSdf = new SimpleDateFormat ("yyyy-MM-dd HH: mm: ss "); private static SimpleDateFormat logDay = new SimpleDateFormat ("dd"); private static SimpleDateFormat logTime = new SimpleDateFormat ("yyyy-MM "); /*** open the log file and write the log ** @ return ***/public static void writeLogtoFile (String mylogtype, Stri Ng tag, String text) {delFile (); Date nowtime = new Date (); String needWriteMessage = LogSdf. format (nowtime) + "" + tag + "\ n" + text + "\ n"; String logFileName; String logFolder = logTime. format (new Date (); if (mylogtype = "error") {logFileName = "error (" + logDay. format (new Date () + "). log ";} else if (mylogtype =" crash ") {logFileName =" crash ("+ logDay. format (new Date () + "). log ";} else {logFileName =" info (" + LogDay. format (new Date () + "). log";} File file = new File (LOG_PATH_SDCARD_DIR + logFolder); if (! File. exists () {file. mkdirs ();} File f = new File (LOG_PATH_SDCARD_DIR + logFolder, logFileName); try {FileWriter filerWriter = new FileWriter (f, true); BufferedWriter bufWriter = new BufferedWriter (filerWriter ); bufWriter. write (needWriteMessage); bufWriter. newLine (); bufWriter. close (); filerWriter. close ();} catch (IOException e) {e. printStackTrace () ;}}/*** Delete the specified Log File **/private static void delFile () {String needDelFiel = logTime. format (getDateBefore (); File file = new File (LOG_PATH_SDCARD_DIR, needDelFiel); if (file. exists () {file. delete () ;}} private static Date getDateBefore () {Date nowtime = new Date (); Calendar now = Calendar. getInstance (); now. setTime (nowtime); now. set (Calendar. DATE, now. get (Calendar. DATE)-SDCARD_LOG_FILE_SAVE_DAYS); return now. getTime ();}}

Modify the src/android/cordovaHeaLog. java File

Package cordova. plugin. hea. log; import org. apache. cordova. cordovaPlugin; import org. apache. cordova. callbackContext; import org. json. JSONArray; import org. json. JSONException; import org. json. JSONObject; import cordova. plugin. hea. log. logUtil;/*** This class echoes a string called from JavaScript. */public class cordovaHeaLog extends CordovaPlugin {@ Override public boolean execute (String action, JSONArray Args, CallbackContext callbackContext) throws JSONException {if (action. equals ("log") {this. log (args. getString (0), args. getString (1), args. getString (2), callbackContext); return true;} return false;} private void log (String mylogtype, String tag, String text, CallbackContext callbackContext) {if (mylogtype! = Null & mylogtype. length ()> 0 & text! = Null & text. length ()> 0 & tag! = Null & tag. length ()> 0) {logUtil. writeLogtoFile (mylogtype, tag, text); callbackContext. success (mylogtype + "" + tag + "" + text);} else {callbackContext. error ("parameter cannot be blank ");}}}

Next, modify www/cordovaHeaLog. js. js

var exec = require('cordova/exec');exports.log = function(arg0,arg1,arg2,success, error) {exec(success, error, "Logjava", "log", [arg0,arg1,arg2]);};

The point is, the plug-in. xml file under the project, I stepped on here for a long time before jumping out.

We will change it to this

<?xml version='1.0' encoding='utf-8'?><plugin id="cordova-plugin-hea-log" version="1"  xmlns="http://apache.org/cordova/ns/plugins/1.0"  xmlns:android="http://schemas.android.com/apk/res/android"> <name>cordovaHeaLog</name> <js-module name="cordovaHeaLog" src="www/cordovaHeaLog.js">  <clobbers target="cordovaHeaLog" /> </js-module> <platform name="android">  <config-file parent="/*" target="res/xml/config.xml">   <feature name="Logjava">    <param name="android-package" value="cordova.plugin.hea.log.cordovaHeaLog" />   </feature>  </config-file>  <config-file parent="/*" target="AndroidManifest.xml"></config-file>  <source-file src="src/android/cordovaHeaLog.java" target-dir="src/cordova/plugin/hea/log/cordovaHeaLog" />  <source-file src="src/android/logUtil.java" target-dir="src/cordova/plugin/hea/log/logUtil" /> </platform></plugin>

5. add custom plug-ins

In general, this is how to add a plug-in.

cordova plugin add cordova-plugin-hea-log

If you want to add a local plug-in, such as my custom plug-in

In this path, add E: \ cordovaHeaLog.

cordova plugin add E:\cordovaHeaLog

Explanation: Why is addcordova-plugin-hea-log? Please go up, because the id in plugin. xml is cordova-plugin-hea-log.

Result:

6. Add the Android platform, Set permissions, use the plug-in, and run the command to view the results.

Add an Android platform

cordova platform add android

Then, in the project path, the HeaIonic/android/AndroidManifest. xml file

Add permission because you want to write logs to sdcard

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

How to Use the plug-in?

Open the file cordova_plugins.js in the path HeaIonic/platforms/android/assets/www.

We can see this

We use this on the page

Enclose the added code

Then ionic serve and cordova build android

Use android studio to package the project and run it. For details about how to package the project, refer to here → ionic2 package it into android apk using cordova

Result: The agent logs are successfully written.

 

Summary:

1. I feel that I have encountered the most problems in the plugin. xml configuration. Therefore, first understand how to configure plugin. xml.

2. For example, the logUtil. java file can be copied to the plug-in after the test function is completed.

3. for debugging, if there is a problem after adding the plug-in, you can check the problem in the Logcat window of android studio and debug it. It will output the problem and solve it by yourself. At the beginning, I was also overwhelmed. I don't know where to debug the plug-in. After writing it, it's not a one-time job. I always need to debug it and see where there will be errors, after all, I am a cainiao.

See: Android plug-in Development Guide → Android Plugin Development Guide

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.