简体   繁体   English

Android JNI广播到Java

[英]Android jni broadcast to java

I'm currently working on (an existing) Android app using native c++ code. 我目前正在使用本机c ++代码开发(现有)Android应用程序。 I want send a broadcast to another Android Java app listening to a BroadcastReceiver. 我想向另一个Android Java应用程序发送广播,以监听BroadcastReceiver。 The receiving app is yet working, but I can't figure out how to broadcast data from JNI code either directly or by sending the values to java code and them broadcasting it from Java. 接收应用程序仍在工作,但是我无法弄清楚如何直接从JNI代码广播数据,或通过将值发送到Java代码然后从Java广播数据。

例

I hope my explanaion is clear. 我希望我的解释清楚。 Can someone help me on how to accomplish this? 有人可以帮我实现这一目标吗?

Thanks! 谢谢!

The easiest way is probably to do it in Java and write a JNI callback to call that Java function. 最简单的方法可能是在Java中执行此操作并编写JNI回调以调用该Java函数。 If you do need to do it in C, you'll need to use JNI to create an Intent, then to set the action and extras of the intent, then use JNI to call the sendBroadcast method of your activity to actually send it. 如果确实需要在C中执行此操作,则需要使用JNI创建一个Intent,然后设置该Intent的操作和其他操作,然后使用JNI调用您活动的sendBroadcast方法以实际发送它。 Its a lot of boilerplate JNI code, so I'd try to avoid it. 它有很多样板的JNI代码,因此我会尽量避免使用它。

The easiest way is to implement all logic in a Java method: 最简单的方法是用Java方法实现所有逻辑:

public class MyClass {
  static {
    System.loadLibrary("mylib_jni");
  }

  public static final String ACTION_TEST = "com.example.action.TEST";
  private final LocalBroadCastManager broadcastManager;

  public MyClass(Context context) {
    broadcastManager = LocalBroadcastManager.getInstance(context);
  }

  @SuppressWarnings("unused")
  private void onSendText(String text) {
    final Intent intent = new Intent(ACTION_TEST).putExtra(Intent.EXTRA_TEXT, text);
    broadcastManager.sendBroadcast(intent);
  }

  private native void sendText();   
}

and just call that method from JNI: 只需从JNI调用该方法:

JNIEXPORT void JNICALL Java_com_example_MyClass_1sendText(JNIEnv *env, jobject instance) {
  jclass clazz = (*env)->GetObjectClass(env, instance);
  jmethodID method = (*env)->GetMethodID(env, clazz, "onSendText", "(Ljava/lang/String;)V");
  jstring text = (*env)->NewString(env, "test message");
  (*env)->CallVoidMethod(env, instance, method, text);
}

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

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