Android Bluetooth通信およびWiFi開発

54344 ワード

通常のAndroid Bluetooth機能の開発手順では、システム権限とBluetoothスイッチのステータスモニタリング、デバイススキャン、デバイス接続、Bluetoothデータ通信のいくつかのプロセスが一般的です.Android 4.3システムの後、Bluetooth 4.0(低消費電力Bluetooth)を使用することができます.最も主要な特徴は低消費電力で、普及率が高いことです.現在のBluetoothデバイスとは、ほとんどが4.0デバイス、bleも特に4.0デバイスを指しています.4.0以前の重要なバージョンは2.1バージョン-標準レート/拡張データレート(BR/EDR)と3.0高速Bluetoothバージョンで、これらは総称して古典的なBluetoothと呼ばれています.
低消費電力のBluetoothをサポートするデバイスにBluetooth 4.0を使用させる場合は、次のコードで監視できます.
// AndroidManifest.xml
"android.hardware.bluetooth_le" android:required="false"/>

if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
    Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
    finish();
}

権限モニタリング
まず、対応するBluetooth権限を適用する必要があります.
    //              ,       、           。
    <uses-permission android:name="android.permission.BLUETOOTH"/>
    //                      ,    bluetooth_admin  
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

次に、プログラムの起動時に現在のデバイスがBluetoothをオンにしているかどうかを監視し、オンにしていない場合はシステムBluetooth機能スイッチインタフェースにジャンプしてBluetoothをオンにします.
 // If BT is not on, request that it be enabled.
        // setupChat() will then be called during onActivityResult
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
            // Otherwise, setup the chat session
        } else if (mChatService == null) {
            setupChat();
        }

onActivity Resultでのキャプチャ
public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_ENABLE_BT:
                // When the request to enable Bluetooth returns
                if (resultCode == Activity.RESULT_OK) {
                    // Bluetooth is now enabled, so set up a chat session
                    setupChat();
                } else {
                    // User did not enable Bluetooth or an error occurred
                    Log.d(TAG, "BT not enabled");
                    Toast.makeText(getActivity(), R.string.bt_not_enabled_leaving,
                            Toast.LENGTH_SHORT).show();
                    getActivity().finish();
                }
        }
    }

デバイススキャン
BluetoothAdapterのstartDiscovery()メソッドを呼び出すだけで、近くの他のBluetoothデバイスの検索を開始します.
 /**
     * Start device discover with the BluetoothAdapter
     */
    private void doDiscovery() {
        // If we're already discovering, stop it
        if (mBtAdapter.isDiscovering()) {
            mBtAdapter.cancelDiscovery();
        }

        // Request discover from BluetoothAdapter
        mBtAdapter.startDiscovery();
    }

その後、Bluetoothデバイスが検索されると、システムはブロードキャストを発行し、受信して対応する処理を行うことができます.
 // Register for broadcasts when a device is discovered
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        this.registerReceiver(mReceiver, filter);

        // Register for broadcasts when discovery has finished
        filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        this.registerReceiver(mReceiver, filter);
/**
     * The BroadcastReceiver that listens for discovered devices and changes the title when
     * discovery is finished
     */
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            // When discovery finds a device
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // Get the BluetoothDevice object from the Intent
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                // If it's already paired, skip it, because it's been listed already
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                    mNewDevicesArrayAdapter.add(device.getName() + "
"
+ device.getAddress()); } // When discovery is finished, change the Activity title } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { setProgressBarIndeterminateVisibility(false); setTitle(R.string.select_device); if (mNewDevicesArrayAdapter.getCount() == 0) { //do something here after finished discovery } } } };

せつぞく
検索した他のデバイスで通信を接続する必要があるデバイスを選択し、デバイスのアドレスを入力し、getRemoteDeviceメソッドを呼び出してBluetoothDeviceインスタンスを取得し、接続を確立するためのサブスレッドを開きます.
private void connectDevice(Intent data, boolean secure) {
        // Get the device MAC address
        String address = data.getExtras()
                .getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
        // Get the BluetoothDevice object
        BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
        // Attempt to connect to the device
        mChatService.connect(device, secure);
    }
/**
     * Start the ConnectThread to initiate a connection to a remote device.
     *
     * @param device The BluetoothDevice to connect
     * @param secure Socket Security type - Secure (true) , Insecure (false)
     */
    public synchronized void connect(BluetoothDevice device, boolean secure) {
        Log.d(TAG, "connect to: " + device);

        // Cancel any thread attempting to make a connection
        if (mState == STATE_CONNECTING) {
            if (mConnectThread != null) {
                mConnectThread.cancel();
                mConnectThread = null;
            }
        }

        // Cancel any thread currently running a connection
        if (mConnectedThread != null) {
            mConnectedThread.cancel();
            mConnectedThread = null;
        }

        // Start the thread to connect with the given device
        mConnectThread = new ConnectThread(device, secure);
        mConnectThread.start();
        // Update UI 
    }

接続スレッド:ここでdeviceが呼び出されます.createRfcommSocketToServiceRecordメソッドは、UUIDパラメータで汎用識別子である通信用のsocketを作成します.
private class ConnectThread extends Thread {
        private final BluetoothSocket mmSocket;
        private final BluetoothDevice mmDevice;
        private String mSocketType;

        public ConnectThread(BluetoothDevice device, boolean secure) {
            mmDevice = device;
            BluetoothSocket tmp = null;
            mSocketType = secure ? "Secure" : "Insecure";

            // Get a BluetoothSocket for a connection with the
            // given BluetoothDevice
            try {
                if (secure) {
                    tmp = device.createRfcommSocketToServiceRecord(
                            MY_UUID_SECURE);
                } else {
                    tmp = device.createInsecureRfcommSocketToServiceRecord(
                            MY_UUID_INSECURE);
                }
            } catch (IOException e) {
                Log.e(TAG, "Socket Type: " + mSocketType + "create() failed", e);
            }
            mmSocket = tmp;
            mState = STATE_CONNECTING;
        }

        public void run() {
            Log.i(TAG, "BEGIN mConnectThread SocketType:" + mSocketType);
            setName("ConnectThread" + mSocketType);

            // Always cancel discovery because it will slow down a connection
            mAdapter.cancelDiscovery();

            // Make a connection to the BluetoothSocket
            try {
                // This is a blocking call and will only return on a
                // successful connection or an exception
                mmSocket.connect();
            } catch (IOException e) {
                // Close the socket
                try {
                    mmSocket.close();
                } catch (IOException e2) {
                    Log.e(TAG, "unable to close() " + mSocketType +
                            " socket during connection failure", e2);
                }
                connectionFailed();
                return;
            }

            // Reset the ConnectThread because we're done
            synchronized (BluetoothChatService.this) {
                mConnectThread = null;
            }

            // Start the connected thread
            connected(mmSocket, mmDevice, mSocketType);
        }

        public void cancel() {
            try {
                mmSocket.close();
            } catch (IOException e) {
                Log.e(TAG, "close() of connect " + mSocketType + " socket failed", e);
            }
        }
    }

デバイス接続が完了したら、スレッドの接続を解除し、リソースの浪費を防止し、通信スレッドを作成し、入出力ストリームの受信と送信を維持します.
public synchronized void connected(BluetoothSocket socket, BluetoothDevice
            device, final String socketType) {
        Log.d(TAG, "connected, Socket Type:" + socketType);

        // Cancel the thread that completed the connection
        if (mConnectThread != null) {
            mConnectThread.cancel();
            mConnectThread = null;
        }


        // Start the thread to manage the connection and perform transmissions
        mConnectedThread = new ConnectedThread(socket, socketType);
        mConnectedThread.start();

        // Send the name of the connected device back to the UI Activity
        Message msg = mHandler.obtainMessage(Constants.MESSAGE_DEVICE_NAME);
        Bundle bundle = new Bundle();
        bundle.putString(Constants.DEVICE_NAME, device.getName());
        msg.setData(bundle);
        mHandler.sendMessage(msg);
        // Update UI title
        updateUserInterfaceTitle();
    }

メッセージ転送スレッド:runメソッドはwhileループであり、接続状態にある場合、入力ストリームからデータを取得し、取得したバイトデータをhandleメカニズムでプライマリスレッドに転送して表示します.データを送信する必要がある場合はwriteメソッドを呼び出せばよい.
/**
     * This thread runs during a connection with a remote device.
     * It handles all incoming and outgoing transmissions.
     */
    private class ConnectedThread extends Thread {
        private final BluetoothSocket mmSocket;
        private final InputStream mmInStream;
        private final OutputStream mmOutStream;

        public ConnectedThread(BluetoothSocket socket, String socketType) {
            Log.d(TAG, "create ConnectedThread: " + socketType);
            mmSocket = socket;
            InputStream tmpIn = null;
            OutputStream tmpOut = null;

            // Get the BluetoothSocket input and output streams
            try {
                tmpIn = socket.getInputStream();
                tmpOut = socket.getOutputStream();
            } catch (IOException e) {
                Log.e(TAG, "temp sockets not created", e);
            }

            mmInStream = tmpIn;
            mmOutStream = tmpOut;
            mState = STATE_CONNECTED;
        }

        public void run() {
            Log.i(TAG, "BEGIN mConnectedThread");
            byte[] buffer = new byte[1024];
            int bytes;

            // Keep listening to the InputStream while connected
            while (mState == STATE_CONNECTED) {
                try {
                    // Read from the InputStream
                    bytes = mmInStream.read(buffer);

                    // Send the obtained bytes to the UI Activity
                    mHandler.obtainMessage(Constants.MESSAGE_READ, bytes, -1, buffer)
                            .sendToTarget();
                } catch (IOException e) {
                    Log.e(TAG, "disconnected", e);
                    connectionLost();
                    break;
                }
            }
        }

        /**
         * Write to the connected OutStream.
         *
         * @param buffer The bytes to write
         */
        public void write(byte[] buffer) {
            try {
                mmOutStream.write(buffer);

                // Share the sent message back to the UI Activity
                mHandler.obtainMessage(Constants.MESSAGE_WRITE, -1, -1, buffer)
                        .sendToTarget();
            } catch (IOException e) {
                Log.e(TAG, "Exception during write", e);
            }
        }

        public void cancel() {
            try {
                mmSocket.close();
            } catch (IOException e) {
                Log.e(TAG, "close() of connect socket failed", e);
            }
        }
    }

これで、Bluetoothによるデータ転送のプロセスはほぼ完了しました.ここでは、一般的なBluetooth向けの通信方式です.低消費電力のBluetoothを使用すると、Googleの公式sample:android-BuletoothLeGattを参照してください.
Android WiFi学習
一、WiFiに関する知識
Android WiFiの開発には、近くのWiFiをスキャンしたり、WiFiの開閉を制御したり、WiFiホットスポットを発射したりするなど、基本的な操作を把握する必要があります.AndroidのsdkではWiFi関連の操作類がAndroidにあります.net.wifiバッグの中.次に公式ガイドに従ってAndroidのWiFiの基本操作を学びます.Google開発者の中国サイトapi
主なクラスはScanResult,wifiConfiguration,WifiInfo,WifiManagerである.
ScanResult
主に、検出されたアクセスポイント、アクセスポイントのアドレス、アクセスポイントの名前、アイデンティティ認証、周波数、信号強度などの情報を記述するために使用される.このクラスを開くと、次の情報が表示されます.
  • BSSIDアクセスポイントのアドレスです.ここでは主に、2台のノートパソコンがワイヤレスカードで接続され、双方のワイヤレスカードが割り当てられたアドレスなど、小さな範囲のいくつかのワイヤレスデバイスが接続されて取得されたアドレスを指します.
  • SSIDネットワークの名前は、ネットワークを検索すると、これによって各異なるネットワークアクセスポイントを区別します.
  • Capabilitiesネットワークアクセスの性能は,ここでは主にネットワークの暗号化方式などを判断するためである.
  • Frequency周波数、チャンネルごとにインタラクティブなMHz数.
  • レベルで、主にネットワーク接続の優先度を判断します.

  • wifiConfiguration
    次の6つのサブクラスが含まれます.
  • WifiConfiguration.AuthAlgorthmは暗号化方法を判断するために用いられる.
  • WifiConfiguration.GroupCipherはGroupCipherの方法を用いて暗号化を行う.
  • WifiConfiguration.KeyMgmt取得はKeyMgmtを用いて行った.
  • WifiConfiguration.PairwiseCipherはWPA方式を用いた暗号化を取得する.
  • WifiConfiguration.Protocolは、どのプロトコルを使用して暗号化するかを取得します.
  • wifiConfiguration.Statusは現在のネットワークのステータスを取得します.

  • WifiInfo
    私たちのwifiが接続する後、このクラスで接続されたwifi接続の情報を取得することができます.
  • getBSSID():BSSID
  • を取得
  • getDetailedStateOf():クライアントの接続性を取得する
  • getHiddensSSID():取得SSIDが非表示になっているかどうか
  • getIpAddress():IPアドレス
  • を取得
  • getLinkSpeed():接続を取得する速度
  • getMacAddress():Macアドレス
  • を取得
  • getrssi()は802.11 n:ネットワークの信号
  • を得る
  • getSSID():SSID
  • を取得
  • getSupplicanState():特定のクライアント状態の情報
  • を返す.
    wifiManager
    このクラスはWiFi接続の管理機能を提供し、Contextを呼び出すことができます.getSystemService(Context.WIFI_SERVICE)を取得するには、次のような方法が一般的です.
  • addNetwork(WifiConfiguration config)取得したネットワークのリンク状態情報により、ネットワーク
  • を追加する.
  • calculateSignalLevel(int rssi,int numLevels)計算信号のレベル
  • compareSignalLevel(int rssiA,int rssiB)接続Aと接続B
  • を比較する.
  • createWifiLock(int lockType,String tag)wifiロックを作成し、現在のwifi接続
  • をロックする
  • disableNetwork(int netId)ネットワーク接続を無効にする
  • disconnect()切断
  • enableNetwork(int netId,Boolean disableOthers)接続
  • getConfiguredNetworks()ネットワーク接続のステータスを取得
  • getConnectionInfo()現在の接続の情報を取得
  • getDhcpInfo()DHCPの情報
  • を取得する.
  • getScanResulats()スキャンテストの結果を取得
  • getWifiState()wifiアクセスポイントが有効かどうかを取得
  • isWifiEnabled()wifi接続が有効かどうかを判断する
  • pingSupplicant()ping 1つの接続で、
  • に接続できるか否かを判断する.
  • ressociate()接続の準備ができていなくても
  • に接続する.
  • reconnect()接続の準備ができたら、
  • に接続します.
  • removeNetwork()ネットワーク
  • を削除
  • saveConfiguration()は、構成情報
  • を保持する.
  • setWifiEnabled()接続を有効にする
  • startScan()スキャン開始
  • updateNetwork(WifiConfiguration config)ネットワーク接続の更新の詳細api公式api
  • を参照
    二、WiFi機能の使用
    WiFi権限の設定
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    <uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE"/>

    WiFi管理クラス
    これはネット上で整理されたWiFi関連のツール類で、WiFi開発の多くのシーンで必要とされる方法が実現されています.
    /**
     * WIFI   
     * @author ZHF
     *
     */
    public class WifiAdmin {
        private static  WifiAdmin wifiAdmin = null;
    
        private List mWifiConfiguration; //           (      )
        private List mWifiList; //            
    
        //    Wifi    
        private WifiInfo mWifiInfo;
    
        WifiManager.WifiLock mWifilock; //    wifi      , wifi        
        public WifiManager mWifiManager;
    
        /**
         *        (  )
         * @param context
         * @return
         */
        public static WifiAdmin getInstance(Context context) {
            if(wifiAdmin == null) {
                wifiAdmin = new WifiAdmin(context);
                return wifiAdmin;
            }
            return null;
        }
        private WifiAdmin(Context context) {
            //    Wifi     WIFI_SERVICE
            this.mWifiManager = (WifiManager) context.getSystemService("wifi");
            //      
            this.mWifiInfo = this.mWifiManager.getConnectionInfo();
        }
    
        /**
         *         
         * @param str      
         * @return
         */
        private WifiConfiguration isExsits(String str) {
            Iterator localIterator = this.mWifiManager.getConfiguredNetworks().iterator();
            WifiConfiguration localWifiConfiguration;
            do {
                if(!localIterator.hasNext()) return null;
                localWifiConfiguration = (WifiConfiguration) localIterator.next();
            }while(!localWifiConfiguration.SSID.equals("\"" + str + "\""));
            return localWifiConfiguration;
        }
    
        /**  WifiLock,            **/
        public void AcquireWifiLock() {
            this.mWifilock.acquire();
        }
        /**    WifiLock**/
        public void CreateWifiLock() {
            this.mWifilock = this.mWifiManager.createWifiLock("Test");
        }
        /**  WifiLock**/
        public void ReleaseWifilock() {
            if(mWifilock.isHeld()) { //      
                mWifilock.acquire();
            }
        }
    
    
        /**  Wifi**/
        public void OpenWifi() {
            if(!this.mWifiManager.isWifiEnabled()){ //  wifi   
                this.mWifiManager.setWifiEnabled(true);
            }
        }
        /**  Wifi**/
        public void closeWifi() {
            if(mWifiManager.isWifiEnabled()) {
                mWifiManager.setWifiEnabled(false);
            }
        }
        /**    id wifi**/
        public void disconnectWifi(int paramInt) {
            this.mWifiManager.disableNetwork(paramInt);
        }
    
        /**      **/
        public void addNetwork(WifiConfiguration paramWifiConfiguration) {
            int i = mWifiManager.addNetwork(paramWifiConfiguration);
            mWifiManager.enableNetwork(i, true);
        }
    
        /**
         *           
         * @param index       ID
         */
        public void connectConfiguration(int index) { 
            //                 
            if (index > mWifiConfiguration.size()) { 
                return; 
            } 
            //        ID     
            mWifiManager.enableNetwork(mWifiConfiguration.get(index).networkId, true); 
        }
    
        /**
         *   wifi           
         * @param paramWifiConfiguration
         * @param paramBoolean     
         */
        public void createWifiAP(WifiConfiguration paramWifiConfiguration,boolean paramBoolean) {
            try {
                Class localClass = this.mWifiManager.getClass();
                Class[] arrayOfClass = new Class[2];
                arrayOfClass[0] = WifiConfiguration.class;
                arrayOfClass[1] = Boolean.TYPE;
                Method localMethod = localClass.getMethod("setWifiApEnabled",arrayOfClass);
                WifiManager localWifiManager = this.mWifiManager;
                Object[] arrayOfObject = new Object[2];
                arrayOfObject[0] = paramWifiConfiguration;
                arrayOfObject[1] = Boolean.valueOf(paramBoolean);
                localMethod.invoke(localWifiManager, arrayOfObject);
                return;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        /**
         *     wifi  
         * @param ssid   
         * @param passawrd   
         * @param paramInt  3   ,1    ,2     ,3 wap  
         * @param type  "ap"  "wifi"
         * @return
         */
        public WifiConfiguration createWifiInfo(String ssid, String passawrd,int paramInt, String type) {
            //       
            WifiConfiguration localWifiConfiguration1 = new WifiConfiguration();
            //        
            localWifiConfiguration1.allowedAuthAlgorithms.clear();
            localWifiConfiguration1.allowedGroupCiphers.clear();
            localWifiConfiguration1.allowedKeyManagement.clear();
            localWifiConfiguration1.allowedPairwiseCiphers.clear();
            localWifiConfiguration1.allowedProtocols.clear();
    
            if(type.equals("wt")) { //wifi  
                localWifiConfiguration1.SSID = ("\"" + ssid + "\"");
                WifiConfiguration localWifiConfiguration2 = isExsits(ssid);
                if(localWifiConfiguration2 != null) {
                    mWifiManager.removeNetwork(localWifiConfiguration2.networkId); //               
                }
                if(paramInt == 1) { //    
                    localWifiConfiguration1.wepKeys[0] = "";
                    localWifiConfiguration1.allowedKeyManagement.set(0);
                    localWifiConfiguration1.wepTxKeyIndex = 0;
                } else if(paramInt == 2) { //    
                    localWifiConfiguration1.hiddenSSID = true;
                    localWifiConfiguration1.wepKeys[0] = ("\"" + passawrd + "\"");
                } else { //wap  
                    localWifiConfiguration1.preSharedKey = ("\"" + passawrd + "\"");
                    localWifiConfiguration1.hiddenSSID = true;
                    localWifiConfiguration1.allowedAuthAlgorithms.set(0);
                    localWifiConfiguration1.allowedGroupCiphers.set(2);
                    localWifiConfiguration1.allowedKeyManagement.set(1);
                    localWifiConfiguration1.allowedPairwiseCiphers.set(1);
                    localWifiConfiguration1.allowedGroupCiphers.set(3);
                    localWifiConfiguration1.allowedPairwiseCiphers.set(2);
                }
            }else {//"ap" wifi  
                localWifiConfiguration1.SSID = ssid;
                localWifiConfiguration1.allowedAuthAlgorithms.set(1);
                localWifiConfiguration1.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
                localWifiConfiguration1.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
                localWifiConfiguration1.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
                localWifiConfiguration1.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
                localWifiConfiguration1.allowedKeyManagement.set(0);
                localWifiConfiguration1.wepTxKeyIndex = 0;
                if (paramInt == 1) {  //    
                    localWifiConfiguration1.wepKeys[0] = "";
                    localWifiConfiguration1.allowedKeyManagement.set(0);
                    localWifiConfiguration1.wepTxKeyIndex = 0;
                } else if (paramInt == 2) { //    
                    localWifiConfiguration1.hiddenSSID = true;//      ssid
                    localWifiConfiguration1.wepKeys[0] = passawrd;
                } else if (paramInt == 3) {//wap  
                    localWifiConfiguration1.preSharedKey = passawrd;
                    localWifiConfiguration1.allowedAuthAlgorithms.set(0);
                    localWifiConfiguration1.allowedProtocols.set(1);
                    localWifiConfiguration1.allowedProtocols.set(0);
                    localWifiConfiguration1.allowedKeyManagement.set(1);
                    localWifiConfiguration1.allowedPairwiseCiphers.set(2);
                    localWifiConfiguration1.allowedPairwiseCiphers.set(1);
                }
            }
            return localWifiConfiguration1;
        }
    
        /**     **/
        public String getApSSID() {
            try {
                Method localMethod = this.mWifiManager.getClass().getDeclaredMethod("getWifiApConfiguration", new Class[0]);
                if (localMethod == null) return null;
                Object localObject1 = localMethod.invoke(this.mWifiManager,new Object[0]);
                if (localObject1 == null) return null;
                WifiConfiguration localWifiConfiguration = (WifiConfiguration) localObject1;
                if (localWifiConfiguration.SSID != null) return localWifiConfiguration.SSID;
                Field localField1 = WifiConfiguration.class .getDeclaredField("mWifiApProfile");
                if (localField1 == null) return null;
                localField1.setAccessible(true);
                Object localObject2 = localField1.get(localWifiConfiguration);
                localField1.setAccessible(false);
                if (localObject2 == null)  return null;
                Field localField2 = localObject2.getClass().getDeclaredField("SSID");
                localField2.setAccessible(true);
                Object localObject3 = localField2.get(localObject2);
                if (localObject3 == null) return null;
                localField2.setAccessible(false);
                String str = (String) localObject3;
                return str;
            } catch (Exception localException) {
            }
            return null;
        }
    
        /**  wifi **/
        public String getBSSID() {
            if (this.mWifiInfo == null)
                return "NULL";
            return this.mWifiInfo.getBSSID();
        }
    
       /**         **/
        public List getConfiguration() {
            return this.mWifiConfiguration;
        }
    
        /**  ip  **/
        public int getIPAddress() {
            return (mWifiInfo == null) ? 0 : mWifiInfo.getIpAddress();
        }
        /**      (Mac)**/
        public String getMacAddress() {
             return (mWifiInfo == null) ? "NULL" : mWifiInfo.getMacAddress();
        }   
    
        /**    id**/
        public int getNetworkId() {
             return (mWifiInfo == null) ? 0 : mWifiInfo.getNetworkId();
        }
        /**        **/
        public int getWifiApState() {
            try {
                int i = ((Integer) this.mWifiManager.getClass()
                        .getMethod("getWifiApState", new Class[0])
                        .invoke(this.mWifiManager, new Object[0])).intValue();
                return i;
            } catch (Exception localException) {
            }
            return 4;   //  wifi    
        }
        /**  wifi    **/
        public WifiInfo getWifiInfo() {
            return this.mWifiManager.getConnectionInfo();
        }
        /**       **/
        public List getWifiList() {
            return this.mWifiList;
        }
    
        /**      **/
        public StringBuilder lookUpScan() {
            StringBuilder localStringBuilder = new StringBuilder();
            for (int i = 0; i < mWifiList.size(); i++)
            {
                localStringBuilder.append("Index_"+new Integer(i + 1).toString() + ":");
                // ScanResult           
                //     :BSSID、SSID、capabilities、frequency、level
                localStringBuilder.append((mWifiList.get(i)).toString());
                localStringBuilder.append("
    "
    ); } return localStringBuilder; } /** wifi **/ public void setWifiList() { this.mWifiList = this.mWifiManager.getScanResults(); } /** wifi**/ public void startScan() { this.mWifiManager.startScan(); } /** BSSID**/ public String GetBSSID() { return (mWifiInfo == null) ? "NULL" : mWifiInfo.getBSSID(); } }

    WiFiホットスポットの作成
    WiFiホットスポットを作成するには、まずwifiのサービスを取得し、ホットスポット名、パスワードなどを構成してから、setWifiApEnabledメソッドを反射的に呼び出すことでホットスポットを作成する必要があります.wifiとホットスポットは同時に開くことができないので、ホットスポットを開くときはwifi Managementを呼び出す必要があります.setWifiEnabled(false); wifiを閉じる
     public void stratWifiAp() {  
            Method method1 = null;  
            try {  
                method1 = mWifiManager.getClass().getMethod("setWifiApEnabled",  
                        WifiConfiguration.class, boolean.class);  
                WifiConfiguration netConfig = new WifiConfiguration();  
    
                netConfig.SSID = mSSID;  
                netConfig.preSharedKey = mPasswd;  
    
                netConfig.allowedAuthAlgorithms  
                        .set(WifiConfiguration.AuthAlgorithm.OPEN);  
                netConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);  
                netConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);  
                netConfig.allowedKeyManagement  
                        .set(WifiConfiguration.KeyMgmt.WPA_PSK);  
                netConfig.allowedPairwiseCiphers  
                        .set(WifiConfiguration.PairwiseCipher.CCMP);  
                netConfig.allowedPairwiseCiphers  
                        .set(WifiConfiguration.PairwiseCipher.TKIP);  
                netConfig.allowedGroupCiphers  
                        .set(WifiConfiguration.GroupCipher.CCMP);  
                netConfig.allowedGroupCiphers  
                        .set(WifiConfiguration.GroupCipher.TKIP);  
    
                method1.invoke(mWifiManager, netConfig, true);  
    
            } catch (IllegalArgumentException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
            } catch (IllegalAccessException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
            } catch (InvocationTargetException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
            } catch (SecurityException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
            } catch (NoSuchMethodException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
            }  
        }  

    参考記事:Androidが開発したBluetooth通信Android Bulutooth Chat AndroidにおけるWiFi開発のまとめ