在Cordova插件中创建自定义的android.app.Application

Bag*_*yer 1 android cordova

我是Cordova插件的新手。我想知道是否可以在我的Android插件中创建自定义的android.app.Application?谢谢

Dav*_*den 5

可以这样做,但是您需要在中的<application>元素中添加对应用程序类的名称引用AndroidManifest.xml。一种方法是after_prepare在每个Cordova准备操作之后,使用挂钩脚本将其应用于清单。例如:

plugin.xml

<plugin xmlns="http://www.phonegap.com/ns/plugins/1.0" 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    id="cordova-plugin-myplugin" 
    version="1.0.0">

  <name>My Plugin</name>

  <platform name="android">

    <config-file target="config.xml" parent="/*">
      <feature name="MyPlugin" >
        <param name="android-package" value="my.package.MyPlugin"/>
      </feature>
    </config-file>

    <js-module name="MyPlugin" src="myplugin.js">
        <clobbers target="MyPlugin"/>
    </js-module>

    <source-file src="MyPlugin.java" target-dir="src/my/package" />
    <source-file src="MyApplication.java" target-dir="src/my/package" />

    <hook type="after_prepare" src="add_application_name.js" />

  </platform>
</plugin>
Run Code Online (Sandbox Code Playgroud)

add_application_name.js

#!/usr/bin/env node

module.exports = function(context) {

  var APPLICATION_CLASS = "my.package.MyApplication";

  var fs = context.requireCordovaModule('fs'),
      path = context.requireCordovaModule('path');

  var platformRoot = path.join(context.opts.projectRoot, 'platforms/android');
  var manifestFile = path.join(platformRoot, 'AndroidManifest.xml');

  if (fs.existsSync(manifestFile)) {
    fs.readFile(manifestFile, 'utf8', function (err, data) {
      if (err) {
        throw new Error('Unable to find AndroidManifest.xml: ' + err);
      }

      if (data.indexOf(APPLICATION_CLASS) == -1) {
        var result = data.replace(/<application/g, '<application android:name="' + APPLICATION_CLASS + '"');
        fs.writeFile(manifestFile, result, 'utf8', function (err) {
          if (err) throw new Error('Unable to write into AndroidManifest.xml: ' + err);
        })
      }
    });
  }
};
Run Code Online (Sandbox Code Playgroud)

MyApplication.java

package my.package;

import android.app.Application;

public class MyApplication extends Application
{
    public static final String TAG = "MyApplication";

    @Override
    public void onCreate()
    {
        Log.d(TAG, "onCreate()");
        // DO SOME STUFF
        super.onCreate();
    }
}
Run Code Online (Sandbox Code Playgroud)