2

我正在尝试为 Cordova - android 创建一个自定义插件。该插件的目的是在点击 HTML5 屏幕上的按钮时引发原生 android 活动的意图。所以最初,我会在一个带有按钮的 HTML5 屏幕上。单击按钮后,我应该被重定向到本机 android 活动屏幕。

这是我已经完成的一些代码,

customplugin.js

function CustomPlugin(){};

CustomPlugin.prototype.launchActivity = function(startClass) 
{
alert("@@@ Starting plugin to launch native activity.");
cordova.exec(null, null, 'CustomPlugin', 'launchActivity', [startClass]);
};

if(!window.plugins) {
window.plugins = {};
}
if (!window.plugins.customplugin) {
   window.plugins.customplugin = new CustomPlugin();
}

但是,在此代码中,我收到“未捕获的类型错误:无法调用未定义的方法“launchActivity”。请帮助我提供一些示例代码示例。提前致谢。

自定义插件.java

package org.apache.cordova.example;

import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaPlugin;
import org.apache.cordova.api.Plugin;
import org.apache.cordova.api.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;

import android.util.Log;

public class CustomPlugin extends CordovaPlugin 
{
@Override
    public boolean execute(String action, final JSONArray args, CallbackContext callbackContext) throws JSONException 
    {
        if ("launchActivity".equals(action)) 
        { 
              String goClass = null; if(args.length() > 0) goClass = args.getString(0);

              Log.i("NATIVE", "Launch class : " + goClass); 
              return true;
          } 
          else 
          { 
              return false;
          }
    }
4

2 回答 2

3

在您的代码片段中,我看不到您实际执行的位置launchActivity()。最好将其添加到问题中,因为似乎存在问题。

首先,确保您的页面中加载了cordova.js 。然后你使用cordova.exec(这是一个使用require.js的例子,但这不是必须的,你也可以使用cordova.exec()

define(['cordova'], function (cordova) {
    'use strict';

    var exec = cordova.require('cordova/exec');

    return {
        changeBackground : function (color) {
            exec(function () {}, function () {}, 'Navbar', 'changeBackground', [color]);
        }
    };

});

确保在res/xml/plugins.xml中添加插件:

<plugin name="Navbar" value="my.package.NavbarPlugin"/>

要创建插件,您只需扩展org.apache.cordova.api.CordovaPlugin.

public class NavbarPlugin extends CordovaPlugin {

    @Override
    public boolean execute(String action, final JSONArray args, CallbackContext callbackContext) throws JSONException {
        if ("changeBackground".equals(action)) { ... }
    }

}

编辑:

它不起作用的问题是因为您正在执行window.customplugin.launchActivity(...). window.customplugin不存在,因此你得到你不能调用launchActivity.undefined

你需要打电话window.plugins.customplugin.launchActivity(...)

于 2013-01-12T16:30:42.887 回答
2

请找到下面的代码片段,为 android 创建原生 Cordova 插件以及调用所需的配置并从 Web 端获取响应。

示例:使用 Cordova 原生插件的 android 设备的当前位置纬度和经度。

安卓代码:

 package com.sample.activity;

 import android.app.Activity;
 import android.content.Context
 import android.location.Criteria;
 import android.location.Location;
 import android.location.LocationListener;
 import android.location.LocationManager;
 import android.os.Bundle;
 import android.util.Log;

public class LocationTrackPlugin extends CordovaPlugin implements LocationListener {
public static final String ACTION_START = "GetLocation";
public static CallbackContext callbackContext;
public static Activity activity;

@Override
public boolean execute(String action, final JSONArray jArray,
                       final CallbackContext callbackContext) throws JSONException {
    activity = this.cordova.getActivity();
    boolean result = false;
    if (ACTION_START.equalsIgnoreCase(action)) {
        LocationTrackPlugin.callbackContext = callbackContext;
        LocationManager locationManager = (LocationManager) activity
                .getSystemService(activity.LOCATION_SERVICE);

        if (!locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            PluginResult pluginResult = new PluginResult(
                    PluginResult.Status.OK, "false");
            pluginResult.setKeepCallback(true);
            try {
                callbackContext.sendPluginResult(pluginResult);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {

            result = true;
            Location location = getCurrentDeviceLocation(activity);
            String my_location = location.getLatitude() + ":" + location.getLongitude();
            PluginResult pluginResult = new PluginResult(
                    PluginResult.Status.OK, my_location);
            pluginResult.setKeepCallback(true);
            try {
                callbackContext.sendPluginResult(pluginResult);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

    }

    return result;

}


public Location getCurrentDeviceLocation(Context contxt) {
    LocationManager locationManager;
    String provider;
    Location location = null;
    locationManager = (LocationManager) contxt
            .getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    provider = locationManager.getBestProvider(criteria, false);

    if (provider != null && !provider.equals("")) {
        location = getCurrentLocation(provider, locationManager);
        if (location != null) {
            locationManager.removeUpdates(this);
            return location;

        } else {
            location = getCurrentLocation(LocationManager.NETWORK_PROVIDER,
                    locationManager);
            if (location != null) {
                locationManager.removeUpdates(this);
                return location;
            } else {
                locationManager.removeUpdates(this);
            }
        }
    } else
        Log.d("Location", "No Provider Found");
    return location;
}

public Location getCurrentLocation(String provider,
                                   LocationManager locationManager) {
    Location newlocation = null;
    if (locationManager.isProviderEnabled(provider)) {
        locationManager.requestLocationUpdates(provider, 1000, 1, this);
        if (locationManager != null) {
            newlocation = locationManager.getLastKnownLocation(provider);
            return newlocation;
        }
    }
    return newlocation;
}

@Override
public void onLocationChanged(Location location) {
    // TODO Auto-generated method stub

}

@Override
public void onProviderDisabled(String provider) {
    // TODO Auto-generated method stub

}

@Override
public void onProviderEnabled(String provider) {
    // TODO Auto-generated method stub

}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
    // TODO Auto-generated method stub

}
}

清单文件.xml

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

Config.xml(文件位于 appname/cordova/Config.xml)

 <feature name="LocationTrackPlugin">
    <param name="android-package"   value=com.sample.activity.LocationTrackPlugin" />
</feature>

ShowLocation.js

  callGetlocationPlugin: function() {
    if (Ext.os.is('Android')) {
        cordova.exec(
                function(result) {
                    console.log("Native call success", result);
                                      },
                function() {
                    console.log('Native call failed');
                },
                'LocationTrackPlugin', 'GetLocation', null);
    }
}
于 2015-12-29T06:53:13.840 回答