How to send (from Native code) a android.content.Context parameter to a Java fct (via JNI)

I am developping an application for my android phone, and I am trying to enable the Wifi hotspot. I am using Qt 5.4.1 so I developp in C++. As there is not any function to do this in the NDK, I am using JNI to call Java Methods.

My java code is (thanks to Ashish Sahu's answer in stackoverflow thread) :

package; import android.content.*; import*; import java.lang.reflect.*; //Class that handles Wifi Hotspot (access point) configuration public class ApManager { //Is Wifi hotspot on or off ? public static boolean isApOn(Context context) { WifiManager wifimanager = (WifiManager) context.getSystemService(context.WIFI_SERVICE); try { Method method = wifimanager.getClass().getDeclaredMethod("isWifiApEnabled"); method.setAccessible(true); return (Boolean) method.invoke(wifimanager); } catch (Throwable ignored) {} return false; } //Turn Wifi hotspot on or off public static boolean configApState(Context context, boolean b) { WifiManager wifimanager = (WifiManager) context.getSystemService(context.WIFI_SERVICE); WifiConfiguration wificonfiguration = null; try { //if Wifi is on, turn it off if(isApOn(context)) { wifimanager.setWifiEnabled(false); } Method method = wifimanager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class); method.invoke(wifimanager, wificonfiguration, b); return true; } catch(Exception e) { e.printStackTrace(); } return false; } }

C++ code sample :

setWifiApEnabled(QAndroidJniObject context, bool b) { return QAndroidJniObject::callStaticMethod<jboolean>("org/app/test/ApManager" , "configApState" , "(Ljava/lang/Object;Z)Z" //Or (Landroid/content/Context;Z)Z ??? , context.object<jobject>() , b); }

But now I have a problem ; how to get the parameter context to pass to the function setWifiApEnabled(context, b) when I call it ?

I am a little lost, I read some threads about this problem (like this one) but I do not totally understand what the people who answered meant.

Could you help me with this ?

EDIT : I found on this stackoverflow thread a way to get the context :

interface = QApplication::platformNativeInterface(); activiti = (jobject)interface->nativeResourceForIntegration("QtActivity"); at = new QAndroidJniObject(activiti); appctx = at->callObjectMethod("getApplicationContext", "()Landroid/content/Context;"); if(appctx.isValid()) qDebug() << "I am valid !"; else qDebug() << "I ain't valid !";

appctx is valid, but the Wifi hotspot doesn't get enabled and I cannot get its state.

EDIT 2 : : I successfully managed to enable the Wifi hotspot in java, using Android Studio. The code is the following : :

public class WifiApManager { private WifiManager wifiMan; protected Method setWifiApEnabledMethod, isWifiApEnabledMethod; protected final static int MAX_ITER = 10; public WifiApManager(WifiManager wifiMan) { this.wifiMan = wifiMan; getHiddenMethods(); } private void getHiddenMethods() { try { setWifiApEnabledMethod = wifiMan.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class); isWifiApEnabledMethod = wifiMan.getClass().getMethod("isWifiApEnabled"); } catch (NoSuchMethodException e) { e.printStackTrace(); } } public boolean isWifiApEnabled() { try { return (Boolean)isWifiApEnabledMethod.invoke(wifiMan); } catch (Exception e) { return false; } } public boolean isWifiEnabled() { return wifiMan.isWifiEnabled(); } public boolean setWifiApEnabled(WifiConfiguration conf, boolean enabled) { try { return (Boolean) setWifiApEnabledMethod.invoke(wifiMan, conf, true); } catch (Exception e) { return false; } } public boolean toggleWifi(String ssid) { // WifiConfiguration creation: WifiConfiguration conf = new WifiConfiguration(); conf.SSID = ssid; conf.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN); // If AP Wifi is enabled, disables it and returns: if(isWifiApEnabled()) { //setWifiApEnabled(null, false); Won't work, see two further lines wifiMan.setWifiEnabled(true); wifiMan.setWifiEnabled(false); int maxIter = MAX_ITER; while (isWifiApEnabled() && maxIter-- >= 0) { try {Thread.sleep(500);} catch (Exception e) {} } return isWifiApEnabled(); } // If standard Wifi is enabled, disables it: if (isWifiEnabled()) { if (wifiMan.setWifiEnabled(false)) { int maxIter = MAX_ITER; while (wifiMan.isWifiEnabled() && maxIter-- >= 0) { try {Thread.sleep(500);} catch (Exception e) {} } } if (isWifiEnabled()) { return false; } } // Enables AP Wifi try { if (! setWifiApEnabled(conf, true)) { System.out.println("setWifiApEnabledMethod failed."); return false; } int maxIter = MAX_ITER; while (! isWifiApEnabled() && maxIter-- > 0) { try {Thread.sleep(500);} catch (Exception e) {} } } catch(Exception e) { e.printStackTrace(); return false; } return true; } }

Main class :

public class AndroidMenusActivity extends Activity implements OnClickListener { private WifiApManager wifiMan; private ToggleButton wifiButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); wifiMan = new WifiApManager((WifiManager) this.getSystemService(Context.WIFI_SERVICE)); setContentView(R.layout.activity_android_menus); makeUI(); } private void makeUI() { LinearLayout subLayout = (LinearLayout) findViewById(; wifiButton = new ToggleButton(this); wifiButton.setTextOn("Disable Wifi"); wifiButton.setTextOff("Enable AP Wifi"); wifiButton.setChecked(wifiMan.isWifiApEnabled()); wifiButton.setOnClickListener(this); subLayout.addView(wifiButton); } @Override public void onClick(View sender) { if (!wifiButton.equals(sender)) return; AsyncTask<Object, Void, Boolean> task = new AsyncTask<Object, Void, Boolean>() { private ToggleButton bt; private WifiApManager wm; @Override protected Boolean doInBackground(Object... args) { bt = (ToggleButton) args[0]; wm = (WifiApManager) args[1]; return wm.toggleWifi(""); } @Override protected void onPostExecute (Boolean result) { bt.setChecked(result.booleanValue()); bt.setEnabled(true); } }; wifiButton.setEnabled(false); task.execute(wifiButton, wifiMan); } }

But I cannot find a way to do the same in C++, any help ?

Category:java Time:2018-11-03 Views:3
Tags: java jni android

Related post

  • How to access resources (like sound, images etc) directly from native code using Android-NDK? 2011-07-19

    I want to know that how can I directly access the resources like images, sound files etc. from native code i.e. C++ files. Actually I am looking for any example that could help me to use the asset_manager_jni.h methods. Looking for suggestions. Thank

  • How to get path to the temp folder from native code on Android? 2012-04-26

    getenv("TMPDIR") returns NULL. Any suggestions on what is temp folder/where to create one? --------------Solutions------------- As far as I know there is no global /tmp in android, you should use the cache dir. Use getCacheDir() to get the "tmp" dir.

  • How to Find memory leaks from native code in android 2011-02-23

    Just wondering if someone knows how to find out memory leaks in native code from android. Google search gives lot of solution, but none of them is full. Please let me know if anybody knows how to do this. --------------Solutions------------- Really u

  • problem displaying bitmap from native code in android 2011-02-11

    I am facing problem with displaying bitmap using native code. My code is as below Native Code JNIEXPORT void JNICALL Java_app_Panel_renderbitmap(JNIEnv* env, jobject obj, jobject bitmap, jlong time_ms) { AndroidBitmapInfo info; void* pixels; int ret;

  • Android: How to broadcast intent from native code? 2010-11-02

    Is it possible to broadcast an Intent from native code? If so, is there documentation and/or sample code pertaining to the relevant APIs? --------------Solutions------------- You will need to call it by calling the Java API function - there is no JNI

  • access android external SD card from native code 2011-03-01

    I'm developing a native apk for android with NDK 5. My question is, how do I access to write and read from external SD card from native code? --------------Solutions------------- It works the same as Java code. You need to use the SDK API Environment

  • How to set the text in a TextBox control from native code? 2011-04-11

    Is it possible to manipulate .net controls from native code? Particularly, I'd like to set the text of a TextBox from some native code. I want it done this way to keep the business logic separated from the user interface, but it is precisely the nati

  • Catching exceptions thrown from native code running on Android 2011-12-07

    The project I'm currently working on requires me to code up the android portion of a cross platform program implementation. A core set of functionality is built and included in my app through android-ndk. I've found that any exception/crash which hap

  • How do I convert a cli::array to a native array from native code? 2011-10-13

    I'm writing a native wrapper around a managed component written in C++\CLI. I have the following function in managed code: array<Byte>^ Class::Function(); I want to expose this function from a native C++ class with the following signature: shar

  • android sdk access java float array from native code 2012-01-18

    i need to get access from native code (C++) to a java vertex array (float array) but i can not find any documentation how to do that.. I can access the object and its non array variables but don't know how to access an array. The code to access a non

  • Access generated Android R class from native code 2011-11-08

    I'm wondering if there is a way to access R class attribute from native code, I need it to read some generated ID that may change every time i do a clean build of my project and I would prefer not to pass them manually to the native part. EDIT As sug

  • can i call java method from native code?if so how? 2011-12-24

    I have a Java function which can take variable number of parameters and in JNI I am receiving all the parameters in jobjectArray. But the problem is all the parameters available in String type,but originally thy are of different datatype. So in c/c++

  • Writing PCM audio data to audio device from native code 2011-03-01

    Is it possible to to write PCM samples to audio device under Android directly from native code? I've been able to reproduce PCM samples by sending data to a socket and playing with AudioTrack. Is it possible to avoid all this path to audio device by

  • NullPointerException when writing to AudioTrack instance in a callback from native code 2012-03-01

    I perform some decoding process in the native code and call a Java method from it to write samples into the AudioTrack instance. Decoding process runs fine, the callback from native code to Java: private void writeToAudioTrack(final byte[] buffer) is

  • need help on jni code(calling java method from native code) 2011-04-24

    I am writing a JNI key logger and the native code for that is as below. #include "com_webspur_rmtadmin_java_app_keylogger_KeyloggerHelper.h" #include "com_webspur_rmtadmin_java_app_keylogger_KeyloggerHelper_KeyListener.h" #include <cstring> #in

  • Is there anyway to get the data connection state of the mobile in the native code of android? 2012-01-10

    Is there anyway of getting the data connection state of the mobile in native code of Android? I know that we can do it with ConnectivityManager in Java. Is there similar kind of thing in native code of Android? As they started supporting native activ

  • Passing byte array from native code to the Java side 2012-03-01

    My goal is passing a byte array of variable length from native code to Java side. The Java class instance method takes bytearray as its argument: private void writeBuffer(final byte[] buffer) { } I am able to find a method ID in the native code: jcla

  • Call into a managed assembly from native code on Windows CE 2009-11-10

    I basically need to expose a C API from a .NET assembly. On the PC, I can use C++/CLI and that works perfectly for what I need. On Windows CE, however, it doesn't look like C++/CLI is supported. Is there any way to do this? --------------Solutions---

  • How to check from .net code whether "Trust access to the VBA project object model" is enabled or not for an Excel application? 2011-03-14

    How to check from .net code whether "Trust access to the VBA project object model" is enabled or not for an Excel application? Manually I can check it from Excel application- File>Options>Trust Center>Trust Center Settings>Macro Settings

Copyright (C), All Rights Reserved.

processed in 0.533 (s). 13 q(s)