Haruyuki Mohri

毛利春幸のブログです。

AndroidのWi-Fi切替(WifiManager)

Using C++Builder 10.2 Tokyo, explain how to switch Wi-Fi on Android.

Manage Wi-Fi switching using JWifiManager

I use di_JWifiManager which wrapped WifiManager.
di_JWifiManager is the Delphi interface.
Set the variable. _di_JWifiManager f_WifiManager; use it like this.

Required headers

Header file for using WifiManager.

#include <Androidapi.JNI.Net.hpp>
#include <Androidapi.Helpers.hpp>
#include <Androidapi.JNI.GraphicsContentViewText.hpp>
#include <Androidapi.JNIBridge.hpp>

Display design

It is a design for displaying on Android.

f:id:mojeld:20171004174435p:plain
TEdit, TSwitch, TTimer, TLabel, was placed.

When the main form creation

Create _di_JWifiManager using TJWifiManager.

//---------------------------------------------------------------------------
void __fastcall Tfm_main_wifistatus::FormCreate(TObject *Sender)
{
    //Form creation.Using TAndroidHelper, get the WIFI_SERVICE.
    _di_JObject obj = TAndroidHelper::Activity->getSystemService(TJContext::JavaClass->WIFI_SERVICE);
    if (obj != nullptr)
    {
        //Wrap to TJWifiManager.
        f_WifiManager = TJWifiManager::Wrap(_di_ILocalObject(obj)->GetObjectID());
        if (f_WifiManager != nullptr)
        {
            Timer1->Enabled = true;
        }
    }
}

Monitor Wi-Fi status at Timer1 event.

void __fastcall Tfm_main_wifistatus::Timer1Timer(TObject *Sender)
{
    //Use a timer event to monitor the Wi-Fi state.
    //Write state change to Edit1->Text. and It also reflects Switch1->IsChecked.
    Timer1->Enabled = false;
    if (f_WifiManager != nullptr)
    {
        Switch1->IsChecked = f_WifiManager->isWifiEnabled();
        UnicodeString wifistr;
        (Switch1->IsChecked)?wifistr = "true": wifistr = "false";
        Edit1->Text = "f_WifiManager->isWifiEnabled() = " + wifistr;
    }
    Timer1->Enabled = true;
}

When you tap the Switch1.

Change the Wi-Fi status when tapping the Switch1.
This uses the setWifiEnabled() function.

void __fastcall Tfm_main_wifistatus::Switch1Switch(TObject *Sender)
{
    //This is a Switch1 change event.
    Timer1->Enabled = false;
    //Set the value of Switch1->IsChecked to setWifiEnabled()
    f_WifiManager->setWifiEnabled(Switch1->IsChecked);
    TThread::CreateAnonymousThread([this]()
    {
        sleep(1);
        TThread::Synchronize(TThread::CurrentThread, [this]()
        {
            Timer1->Enabled = true;
        });
    })->Start();
}

f:id:mojeld:20171004175329g:plain