简体   繁体   English

如何从Cordova插件调用活动方法?

[英]How to call activity methods from cordova plugin?

How to call methods inside an activity class from cordova plugin class? 如何从cordova插件类中调用活动类中的方法?

// Plugin class
public class BLEPlugin extends CordovaPlugin {

    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {

        if (action.equals("greet")) {
            String name = args.getString(0);
            String message = "Hello, " + name;
            //callbackContext.success(message);
            this.greet(message, callbackContext);
        } else if (action.equals("isBLESupported")) {
            this.isBLESupported(callbackContext);
        }
        return true;
    }


    // Returns true if BLE is supported.
    private void isBLESupported(CallbackContext callbackContext) {
        boolean isSupported = .. ?  // how to access MainActivity method?
        Log.w(TAG, "isSupported: " + isSupported);
        JSONObject params = new JSONObject();
        try {
            params.put("isSupported", isSupported);
        } catch (JSONException execp) {}
        callbackContext.success(params);
    }
}


// Main activity
// ..
public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // ..
    }

    // How to access this method?
    public boolean isBLESupported() {
        return getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE);
    }

    @Override
    protected void onResume() {
        super.onResume();
        // ..
    }
}

in your MainActivity create static Method 在您的MainActivity中创建静态方法

public static boolean isBLESupported(Context c) {

    System.out.println("Activity");
    return c.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE);
}

and in your Cordovaplugin change your method 然后在您的Cordovaplugin中更改您的方法

// Returns true if BLE is supported.
private void isBLESupported(CallbackContext callbackContext) {
    boolean isSupported = MainActivity.isBLESupported(this.cordova.getActivity().getApplicationContext());
    Log.w(TAG, "isSupported: " + isSupported);
    JSONObject params = new JSONObject();
    try {
        params.put("isSupported", isSupported);
    } catch (JSONException execp) {}
    callbackContext.success(params);
}

Or you can directly check boolean from plugin class by cordova context 或者您可以通过cordova上下文直接从插件类检查布尔值

 boolean isSupported = this.cordova.getActivity().getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM