如何从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();
// ..
}
}
答案 0 :(得分:1)
public static boolean isBLESupported(Context c) {
System.out.println("Activity");
return c.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE);
}
并在您的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);
}
或者你可以通过cordova context
直接检查插件类的布尔值 boolean isSupported = this.cordova.getActivity().getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE);