Congratulations to our 2022 Qt Champions!

Android JNI, display AlertDialog for LOCATION permissions

  • I want to show an AlertDialog on my android App to request "Location" permission since it's compulsory from Android API 26. I am using JNI to call a Java function that will prompt the trigger the AlertDialog.

    below is my Java code

        public static void init(String node){
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (m_instance.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    final AlertDialog.Builder builder = new AlertDialog.Builder(m_instance);
                    builder.setTitle("This app needs location access");
                    builder.setMessage("Please grant location access so this app can detect beacons.");
                    builder.setPositiveButton(android.R.string.ok, null);
                    builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
                        public void onDismiss(DialogInterface dialog) {
                            m_instance.requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);

    And this is how i am calling it from my C++ code.

        QAndroidJniObject javaNotification = QAndroidJniObject::fromString("beconNode");

    I am receiving the below error when trying to call the function.

    F art     : art/runtime/] JNI DETECTED ERROR IN APPLICATION: JNI GetStaticMethodID called with pending exception java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
    F art     : art/runtime/]   at void android.os.Handler.<init>(android.os.Handler$Callback, boolean) (
    F art     : art/runtime/]   at void android.os.Handler.<init>() (
    F art     : art/runtime/]   at void<init>(android.content.Context, int, boolean) (
    F art     : art/runtime/]   at void<init>(android.content.Context, int, boolean) (
    F art     : art/runtime/]   at$Builder.create() (
    F art     : art/runtime/]   at$ (
    F art     : art/runtime/]   at void org.qtproject.example.beacorat.Scan.initBT() (
    F art     : art/runtime/]   at void org.qtproject.example.beacorat.Scan.startLeScan(java.lang.String) (

    This crashes the whole App.

    Please help.

  • Moderators


    I'm not very good with java, a reason why I'm very grateful for the QtAndroid modul.

    you can use that one for runtime permission request/check

    This should help you.

Log in to reply