IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Entrée/Sortie Java Discussion :

Activer Hotspot / Récupérer (code c++) le contexte de l'application pour param fonction Java (via JNI)


Sujet :

Entrée/Sortie Java

  1. #1
    Candidat au Club
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Juin 2015
    Messages
    3
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Yvelines (Île de France)

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : Industrie

    Informations forums :
    Inscription : Juin 2015
    Messages : 3
    Points : 3
    Points
    3
    Par défaut Activer Hotspot / Récupérer (code c++) le contexte de l'application pour param fonction Java (via JNI)
    Bonjour,

    Je suis en train de développer une application pour un projet d'école d'ingénieurs, j'utilise QT 5.4.1 (Qt creator 3.4.1, MinGW) sur Windows 7 64 bits.
    Mon application sera assez simple, elle aura juste à activer le hotspot Wifi (Point d'accès), attendre qu'une autre application s'y connecte, et ensuite envoyer un message (String) à cette application

    Comme il n'y a pas de fonction permettant d'activier le hotspot Wifi dans le NDK, j'utilise JNI (Java Native Interface) pour appeller les fonctions Java depuis lecode natif (c++).
    Par exemple, pour une fonction toute simple :
    Code Java :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    package org.app.test;
    import android.os.Vibrator;
     
    public class JniMath {
     
    		public static int fibonacci(int n)
    		{
    				if(n<0)
    						return -1;
    				else if(n==0 || n==1)
    						return n;
     
    				return fibonacci(n-1)+fibonacci(n-2);
    		}
    }
    C++ code :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    int fibonacci(int n)
    {
        return QAndroidJniObject::callStaticMethod<jint>("org/app/test/JniMath"
                                                         , "fibonacci"
                                                         , "(I)I"
                                                         , n);
    }
    Ceci marche très bien, je vais maintenant essayer de faire la même chose avec les fonctions permettant de configurer le hotspot Wifi.
    J'ai une classe Java "ApManager" :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    package org.app.test;
     
    import android.content.*;
    import android.net.wifi.*;
    import java.lang.reflect.*;
     
    //Classe qui gère le Hotspot Wifi (point d'accès)
    public class ApManager {
     
    	//Le hotspot Wifi est-il activé ?
    	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;
    	}
     
    	//(des)Activer le hotspot Wifi
    	public static boolean configApState(Context context, boolean b) {
    		WifiManager wifimanager = (WifiManager) context.getSystemService(context.WIFI_SERVICE);
    		WifiConfiguration wificonfiguration = null;
    		try {
    			//Si le Wifi est activé, le désactiver
    			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 :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    bool getWifiApState(QAndroidJniObject context)
    {
        return QAndroidJniObject::callStaticMethod<jboolean>("org/app/test/ApManager"
                                                             , "isApOn"
                                                             , "(Ljava/lang/Object)Z" //Ou (Landroid/content/Context)Z ????
                                                             , context.object<jobject>());
    }
     
    bool setWifiApEnabled(QAndroidJniObject context, bool b)
    {
        return QAndroidJniObject::callStaticMethod<jboolean>("org/app/test/ApManager"
                                                             , "configApState"
                                                             , "(Ljava/lang/Object;Z)Z" //Ou (Landroid/content/Context;Z)Z ???
                                                             , context.object<jobject>()
                                                             , b);
    }
    Le code me semble correct, j'hésite entre les deux signatures mais j'ai un autre problème plus génant : Je ne vois pas comment, depuis le code C++, obtenir le contexte de l'application, pour pouvoir ensiute le passer comme argument à mes fonctions "bool getWifiApState(QAndroidJniObject context)" et "bool setWifiApEnabled(QAndroidJniObject context, bool b)" ?
    J'avoue avoir un peu de mal à comprendre...

    Je vous remercie d'avance pour vos réponses.

    EDIT : J'ai trouvé :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    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 !";
    Malheureusement, cela ne marche pas, le hotspot Wifi ne s'active pas et je ne'arrive pas à récupérer son état. Même si j'essaie de faire quelque chose de simple comme activer le Wifi (via wifimanager.setWifiEnabled(true), cela ne marche pas non plus
    Une idée ?

    EDIT 2 : C'est assez bizarre, en fait j'ai déjà réussi à activer le Wifi (pas le hotspot), grâce au code natif suivant :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    QAndroidJniObject activity = QAndroidJniObject::callStaticObjectMethod("org/qtproject/qt5/android/QtNative", "activity", "()Landroid/app/Activity;");
    QAndroidJniObject serviceField = QAndroidJniObject::getStaticObjectField<jstring>("android/content/Context", "WIFI_SERVICE");
    QAndroidJniObject wifia = activity.callObjectMethod("getSystemService", "(Ljava/lang/String;)Ljava/lang/Object;", serviceField.object<jobject>());
    wifia.callMethod<jboolean>("setWifiEnabled", "(Z)Z", true);
    Si j'essaie maintenant d'activer le Wifi depuis le code Java, en récupérant "wifia" en paramètre :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    public class ApManager {
     
    	//Is Wifi on or off ?
    	public static boolean isApOn(WifiManager wifimanager) {	
    		return wifimanager.isWifiEnabled();
    	}
     
    	//Turn Wifi on or off
    	public static boolean configApState(WifiManager wifimanager, boolean b) {	
    		return wifimanager.setWifiEnabled(b);
    	}		
    }
    Cela ne marche pas ?
    Cela veut dire qu'il y a un problème au niveau du passage de l'atrgument ?

  2. #2
    Candidat au Club
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Juin 2015
    Messages
    3
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Yvelines (Île de France)

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : Industrie

    Informations forums :
    Inscription : Juin 2015
    Messages : 3
    Points : 3
    Points
    3
    Par défaut
    Je me permets de remonter ce topic car j'ai édité ma question pour ajouter du code

  3. #3
    Candidat au Club
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Juin 2015
    Messages
    3
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Yvelines (Île de France)

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : Industrie

    Informations forums :
    Inscription : Juin 2015
    Messages : 3
    Points : 3
    Points
    3
    Par défaut
    Personne ?

    J'ai réussi à activer le hotspot Wifi avec du code Java, sous Android Studio.

    Classe WifiApManager :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    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;
    	}
    }
    Classe principale :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    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(R.id.subLayout);
    		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("test.com");
    			}
    			@Override
    			protected void onPostExecute (Boolean result) {
    				bt.setChecked(result.booleanValue());
    				bt.setEnabled(true);
    			}
    		};
    		wifiButton.setEnabled(false);
    		task.execute(wifiButton, wifiMan);
    	}
    }
    Mais aucun moyen d'y arriver depuis du code C++...

  4. #4
    Nouveau Candidat au Club
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Octobre 2015
    Messages
    1
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 34
    Localisation : France, Ille et Vilaine (Bretagne)

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Produits et services télécom et Internet

    Informations forums :
    Inscription : Octobre 2015
    Messages : 1
    Points : 1
    Points
    1
    Par défaut Problématique similaire
    Bonjour zarachbaal

    Je voulais savoir si vous aviez fini par réussir à récupérer la connexion au Hotspot wifi depuis le code C++.
    Je suis un peu dans le même cas que vous, je dois me connecter à un réseau WiFi via une application QT. J'y arrive en natif sous Android Studio sans soucis mais je bloque complètement en C++

    Avez-vous de nouvelles pistes à explorer sur ce sujet ?

    Cordialement,

Discussions similaires

  1. Réponses: 1
    Dernier message: 02/07/2010, 11h10
  2. [cURL] Récupérer code source d'une page
    Par sourivore dans le forum Bibliothèques et frameworks
    Réponses: 11
    Dernier message: 17/06/2007, 13h53
  3. [MySQL] Récupérer Code HTML généré par PHP
    Par @ngelofdeath dans le forum PHP & Base de données
    Réponses: 4
    Dernier message: 26/04/2006, 21h51
  4. Récupérer code HTML en JS.
    Par Kernel_Panic dans le forum Général JavaScript
    Réponses: 6
    Dernier message: 27/02/2006, 19h22
  5. Récupérer le nom du contexte d'une webapp
    Par citrouille86 dans le forum Servlets/JSP
    Réponses: 2
    Dernier message: 09/09/2005, 23h59

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo