Skip to content

Instantly share code, notes, and snippets.

Last active November 1, 2023 06:54
Show Gist options
  • Save SaschaWillems/34fa0f1b4f0fe7805640fba7ed80ab2d to your computer and use it in GitHub Desktop.
Save SaschaWillems/34fa0f1b4f0fe7805640fba7ed80ab2d to your computer and use it in GitHub Desktop.
Displaying a native android alert dialog from C++ using JNI
package com.yourpackage.appname;
import java.util.concurrent.Semaphore;
public class MyActivity extends NativeActivity {
static {
// Load native library
protected void onCreate(Bundle savedInstanceState) {
// Use a semaphore to create a modal dialog
private final Semaphore semaphore = new Semaphore(0, true);
// This function will be called from C++ by name and signature
public void showAlert(final String message)
final MyActivity activity = this;
ApplicationInfo applicationInfo = activity.getApplicationInfo();
final String applicationName = applicationInfo.nonLocalizedLabel.toString();
this.runOnUiThread(new Runnable() {
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(activity, AlertDialog.THEME_HOLO_DARK);
builder.setPositiveButton("Close", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
AlertDialog dialog = builder.create();;
try {
catch (InterruptedException e) { }
// androidApp is your native android application object declared like this:
// android_app* androidApp;
void showAlert(const char* message) {
JNIEnv* jni;
androidApp->activity->vm->AttachCurrentThread(&jni, NULL);
jclass clazz = jni->GetObjectClass(androidApp->activity->clazz);
// Get the ID of the method we want to call
// This must match the name and signature from the Java side
// Signature has to match java implementation (second string hints a t a java string parameter)
jmethodID methodID = jni->GetMethodID(clazz, "showAlert", "(Ljava/lang/String;)V");
// Strings passed to the function need to be converted to a java string object
jstring jmessage = jni->NewStringUTF(message);
jni->CallVoidMethod(androidApp->activity->clazz, methodID, jmessage);
// Remember to clean up passed values
Copy link

ghost commented Sep 9, 2020

This is not full c++ code since java code is still being used. I want Alertdialog fully in c++ with both setPositiveButton and setNegativeButton but I don't have knowledge in JNI in c++

Toast in c++ does didn't needed to be written in java like this

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment