中文字幕av专区_日韩电影在线播放_精品国产精品久久一区免费式_av在线免费观看网站

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

【移動開發】Android中WIFI開發總結(二)

發布時間:2020-08-05 20:59:20 來源:網絡 閱讀:27813 作者:zhf651555765 欄目:開發技術

   搞了好幾天終于有點眉目了【移動開發】Android中WIFI開發總結(二),這里接著總結一下Android中WiFi的使用,在前面(http://smallwoniu.blog.51cto.com/3911954/1334951)我們已經簡單了解了Wifi實際操作中所用到的幾個主要類,今天就剖析一個WIFI搜索、創建、關閉、連接及一些簡單的動畫的綜合案例。


首先,我們還是看一下我們項目的框架

【移動開發】Android中WIFI開發總結(二)

MainActivity類:(處理wifi消息,加載UI)

/**
 * 主界面
 * @author ZHF
 *
 */
public class MainActivity extends Activity implements EventHandler{
    //消息事件
    public static final int m_nWifiSearchTimeOut = 0;// 搜索超時
    public static final int m_nWTScanResult = 1;// 搜索到wifi返回結果
    public static final int m_nWTConnectResult = 2;// 連接上wifi熱點
    public static final int m_nCreateAPResult = 3;// 創建熱點結果
    public static final int m_nUserResult = 4;// 用戶上線人數更新命令(待定)
    public static final int m_nWTConnected = 5;// 點擊連接后斷開wifi,3.5秒后刷新adapter
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
    //一些常量
    public static final String PACKAGE_NAME = "com.zhf.wifidemo.wifi";  //應用包名
    public static final String FIRST_OPEN_KEY = "version";  //版本號信息
    public static final String WIFI_AP_HEADER = "zhf_";
    public static final String WIFI_AP_PASSWORD ="zhf12345";
    //wifi操作事件(枚舉)-->方便彈出對話框處理事件
    private int wFOperateEnum = WFOperateEnum.NOTHING;
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
    //三個重要的類
    public WFSearchProcess m_wtSearchProcess; //WiFi搜索進度條線程
    public WifiAdmin m_wiFiAdmin; //Wifi管理類
    public CreateAPProcess m_createAPProcess; //創建Wifi熱點線程
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
    //相關控件
    private WFSearchAnimationFrameLayout m_FrameLWTSearchAnimation;  //自定義雷達動畫布局
    private GifView m_gifRadar;  //wifi信號動畫布局
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
                                                                                                                                                                                                                                                                                                                                                             
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
    private LinearLayout m_linearLCreateAP; //創建熱點View
    private ProgressBar m_progBarCreatingAP; //創建熱點進度條
    private TextView m_textVPromptAP; //創建熱點進度條文字
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
    private Button m_btnBack; //左上角返回按鈕
    private Button m_btnSearchWF; //右上角wifi搜索按鈕
    private Button m_btnCreateWF; //創建wifi熱點
    private ListView m_listVWT; //顯示信息
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
    private LinearLayout m_LinearLDialog; //提醒對話框
    private TextView m_textVContentDialog;  //對話框文本內容
    private Button m_btnConfirmDialog, m_btnCancelDialog; //提醒對話框上的按鈕
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
    private TextView m_textVWTPrompt; //中間文字提示
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
    private boolean m_isFirstOpen = true;  //標記是否是第一次打開
    ArrayList<ScanResult> m_listWifi = new ArrayList();//檢測到熱點信息列表
    private WTAdapter m_wTAdapter; //網絡列表適配器
    public Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
            case m_nWifiSearchTimeOut: // 搜索超時
                m_wtSearchProcess.stop();
                m_FrameLWTSearchAnimation.stopAnimation();
                m_listWifi.clear();  //網絡列表
                //設置控件
                m_textVWTPrompt.setVisibility(View.VISIBLE);
                m_textVWTPrompt.setText("需要重新搜索,點右上角重新搜索或創建新的熱點...");
                break;
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
            case m_nWTScanResult:  //掃描到結果
                m_listWifi.clear();
                if(m_wiFiAdmin.mWifiManager.getScanResults() != null) {
                    for (int i = 0; i < m_wiFiAdmin.mWifiManager.getScanResults().size(); i++) {
                        ScanResult scanResult = m_wiFiAdmin.mWifiManager.getScanResults().get(i);
                        //和指定連接熱點比較,將其他的過濾掉!
                        if(scanResult.SSID.startsWith(WIFI_AP_HEADER)) {
                            m_listWifi.add(scanResult);
                        }
                    }
                    if(m_listWifi.size() > 0) {
                        m_wtSearchProcess.stop();
                        m_FrameLWTSearchAnimation.stopAnimation();
                        m_textVWTPrompt.setVisibility(View.GONE);
                        //更新列表,顯示出搜索到的熱點
                        m_wTAdapter.setData(m_listWifi);
                        m_wTAdapter.notifyDataSetChanged();
                    }
                }
                break;
            case m_nWTConnectResult:  //連接結果
                m_wTAdapter.notifyDataSetChanged(); //刷新適配器數據
                break;
            case m_nCreateAPResult:  //創建wifi熱點結果
                m_createAPProcess.stop();
                m_progBarCreatingAP.setVisibility(View.GONE); //旋轉進度條
                if((m_wiFiAdmin.getWifiApState() == 3 || m_wiFiAdmin.getWifiApState() == 13) && (m_wiFiAdmin.getApSSID().startsWith(WIFI_AP_HEADER))) {
                    //設置控件
                    m_textVWTPrompt.setVisibility(View.GONE);
                    m_linearLCreateAP.setVisibility(View.VISIBLE);
                    m_btnCreateWF.setVisibility(View.VISIBLE);
                    m_gifRadar.setVisibility(View.VISIBLE);
                    m_btnCreateWF.setBackgroundResource(R.drawable.x_ap_close);
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
                    m_textVPromptAP.setText("熱點創建成功!"+ "\n熱點名:"+ m_wiFiAdmin.getApSSID()+ "\n連接密碼:zhf12345");
                } else {
                    m_btnCreateWF.setVisibility(View.VISIBLE);
                    m_btnCreateWF.setBackgroundResource(R.drawable.x_wt_create);
                    m_textVPromptAP.setText("熱點創建失敗,您可以重新創建或者搜索其它熱點");
                }
                break;
            case m_nUserResult :
                //更新用戶上線人數
                break;
            case m_nWTConnected:  //點擊連接后斷開wifi,3.5s后刷新
                m_wTAdapter.notifyDataSetChanged();
                break;
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               
            }
        };
    };
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.wt_main);
        //搜索Wifi
        m_wtSearchProcess = new WFSearchProcess(this);
        //創建Wifi熱點
        m_createAPProcess = new CreateAPProcess(this);
        //wifi管理類
        m_wiFiAdmin  = WifiAdmin.getInstance(this);
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
        //初始化View
        initView();
    }
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
    /**初始化View**/
    private void initView() {
        // 監聽廣播
        WIFIBroadcast.ehList.add(this);
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
        /******************************實例化布局**************************************/
        m_linearLCreateAP = (LinearLayout) findViewById(R.id.create_ap_llayout_wt_main);  //創建熱點View
        m_progBarCreatingAP = (ProgressBar) findViewById(R.id.creating_progressBar_wt_main);  //創建熱點進度條
        m_textVPromptAP = (TextView) findViewById(R.id.prompt_ap_text_wt_main); //創建熱點進度條文字
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
        m_FrameLWTSearchAnimation = ((WFSearchAnimationFrameLayout) findViewById(R.id.search_animation_wt_main));// 搜索時的動畫
        m_listVWT = ((ListView) findViewById(R.id.wt_list_wt_main));// 搜索到的熱點listView
        //注意此處
        m_wTAdapter = new WTAdapter(this, m_listWifi);
        m_listVWT.setAdapter(m_wTAdapter);
        m_textVWTPrompt = (TextView) findViewById(R.id.wt_prompt_wt_main); //中間提醒文字
        m_gifRadar = (GifView) findViewById(R.id.radar_gif_wt_main); //gif動畫
        //提醒對話框布局
        m_LinearLDialog = (LinearLayout) findViewById(R.id.dialog_layout_wt_main);
        m_textVContentDialog = (TextView) findViewById(R.id.content_text_wtdialog);
        m_btnConfirmDialog = (Button) findViewById(R.id.confirm_btn_wtdialog);
        m_btnCancelDialog = (Button) findViewById(R.id.cancel_btn_wtdialog);
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
        //左上角返回鍵
        m_btnBack = (Button) findViewById(R.id.back_btn_wt_main);
        m_btnBack.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed(); //相當于調用系統返回鍵,結束當前Activity
            }
        });
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
        //右上角搜索熱點按鈕
        m_btnSearchWF = (Button) findViewById(R.id.search_btn_wt_main);
        m_btnSearchWF.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!m_wtSearchProcess.running) { //搜索線程沒有開啟
                    //1.當前熱點或wifi連接著    WIFI_STATE_ENABLED 3 //WIFI_AP_STATE_ENABLED  13
                    if(m_wiFiAdmin.getWifiApState() == 3 || m_wiFiAdmin.getWifiApState() == 13) {
                        wFOperateEnum = WFOperateEnum.SEARCH; //搜索wifi事件
                        m_LinearLDialog.setVisibility(View.VISIBLE); ///wifi提示對話框顯示
                        m_textVContentDialog.setText("是否關閉當前熱點去搜索其他熱點?");
                        return;  //跳出此方法,交由對話框來處理事件
                    }
                    //2.當前沒有熱點或wifi連接著
                    if(!m_wiFiAdmin.mWifiManager.isWifiEnabled()) { //如果wifi沒打開
                        m_wiFiAdmin.OpenWifi();
                    }
                    m_textVWTPrompt.setVisibility(View.VISIBLE); //中間提示文字
                    m_textVWTPrompt.setText("正在搜索附近的熱點...");
                    m_linearLCreateAP.setVisibility(View.GONE); //創建wifi熱點布局消失
                    m_gifRadar.setVisibility(View.GONE); //熱點連接動畫消失
                    m_btnCreateWF.setBackgroundResource(R.drawable.x_wt_create); //更改按鈕文字“創建”
                    //開始搜索wifi
                    m_wiFiAdmin.startScan();
                    m_wtSearchProcess.start(); //開啟搜索線程
                    m_FrameLWTSearchAnimation.startAnimation(); //開啟波紋動畫
                }else {//搜索線程開啟著,再次點擊按鈕
                    //重新啟動
                    m_wtSearchProcess.stop();
                    m_wiFiAdmin.startScan();    //開始搜索wifi
                    m_wtSearchProcess.start();
                }
            }
        });
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
        //中間創建wifi熱點按鈕
        m_btnCreateWF = (Button) findViewById(R.id.create_btn_wt_main);
        m_btnCreateWF.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if(m_wiFiAdmin.getWifiApState() == 4) { // WIFI_STATE_UNKNOWN
                    Toast.makeText(getApplicationContext(),"您的設備不支持熱點創建!", Toast.LENGTH_SHORT).show();
                    return;
                }
                if(m_wiFiAdmin.mWifiManager.isWifiEnabled()) { //目前連著wifi
                    wFOperateEnum = WFOperateEnum.CREATE;  //wifi熱點創建事件
                    m_LinearLDialog.setVisibility(View.VISIBLE); //對話框可用
                    m_textVContentDialog.setText("創建熱點會關閉當前的WiFi,確認繼續?");
                    return;
                }
                if((m_wiFiAdmin.getWifiApState() == 3 || m_wiFiAdmin.getWifiApState() == 13)
                        && (!m_wiFiAdmin.getApSSID().startsWith(WIFI_AP_HEADER))) {//目前連接著其他熱點名
                    wFOperateEnum = WFOperateEnum.CREATE;  //wifi熱點創建事件
                    m_LinearLDialog.setVisibility(View.VISIBLE);
                    m_textVContentDialog.setText("系統熱點被占用,點確定開啟熱點以傳輸文件!");
                    return;
                }
                if (((m_wiFiAdmin.getWifiApState() == 3) || (m_wiFiAdmin.getWifiApState() == 13))
                        && (m_wiFiAdmin.getApSSID().startsWith(WIFI_AP_HEADER))) {//目前連接著自己指定的Wifi熱點
                    wFOperateEnum = WFOperateEnum.CLOSE;  //wifi熱點關閉事件
                    m_LinearLDialog.setVisibility(View.VISIBLE);
                    m_textVContentDialog.setText("關閉熱點會中斷當前傳輸,您確定這么做?");
                    return;
                }
                if(m_wtSearchProcess.running) {
                    m_wtSearchProcess.stop(); //停止線程
                    m_FrameLWTSearchAnimation.stopAnimation(); //停止動畫
                }
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
                /******************點擊創建熱點時沒有連接wifi或熱點的情況*****************************/
                //關閉Wifi
                m_wiFiAdmin.closeWifi();
                //創建熱點(名字,密碼,加密類型,wifi/ap類型)
                m_wiFiAdmin.createWifiAP(m_wiFiAdmin.createWifiInfo(WIFI_AP_HEADER + getLocalHostName(), WIFI_AP_PASSWORD, 3, "ap"), true);
                m_createAPProcess.start(); //開啟創建熱點線程
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
                //將wifi信息列表設置到listview中
                m_listWifi.clear();
                m_wTAdapter.setData(m_listWifi);
                m_wTAdapter.notifyDataSetChanged();
                //設置布局
                m_linearLCreateAP.setVisibility(View.VISIBLE); //熱點布局可用
                m_progBarCreatingAP.setVisibility(View.VISIBLE);
                m_textVPromptAP.setText("正在創建熱點"); //進度條文字
                m_btnCreateWF.setVisibility(View.GONE); //點擊一次不可再點
                m_textVWTPrompt.setVisibility(View.GONE);
            }
        });
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
        //對話框確認按鈕
        m_btnConfirmDialog.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                m_LinearLDialog.setVisibility(View.GONE); //讓對話框布局消失
                switch (wFOperateEnum) { //根據wifi操作事件
                case WFOperateEnum.CLOSE:  //關閉wifi熱點
                    //設置布局
                    m_textVWTPrompt.setVisibility(View.VISIBLE);
                    m_textVWTPrompt.setText("熱點已關閉!可以進行其他操作了!"); //中間提醒文字
                    m_btnCreateWF.setBackgroundResource(R.drawable.x_wt_create); //按鈕文字改回“創建”
                    m_gifRadar.setVisibility(View.GONE); //熱點動畫停止
                    m_linearLCreateAP.setVisibility(View.GONE); //下部創建熱點布局不可用
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
                    //關閉熱點
                    m_wiFiAdmin.createWifiAP(m_wiFiAdmin.createWifiInfo(m_wiFiAdmin.getApSSID(), "zhf123456", 3, "ap"), false);
                    break;
                case WFOperateEnum.CREATE:  //創建wifi熱點
                    if(m_wtSearchProcess.running) {
                        m_wtSearchProcess.stop();  //搜索wifi線程停止
                        m_FrameLWTSearchAnimation.stopAnimation(); //搜索wifi動畫停止
                    }
                    //關閉wifi
                    m_wiFiAdmin.closeWifi();
                    //創建WiFi熱點
                    m_wiFiAdmin.createWifiAP(m_wiFiAdmin.createWifiInfo(WIFI_AP_HEADER + getLocalHostName(), WIFI_AP_PASSWORD, 3, "ap"),true);
                    m_createAPProcess.start();
                    //刷新listView布局
                    m_listWifi.clear();
                    m_wTAdapter.setData(m_listWifi);
                    m_wTAdapter.notifyDataSetChanged();
                    //設置布局
                    m_linearLCreateAP.setVisibility(View.VISIBLE);
                    m_progBarCreatingAP.setVisibility(View.VISIBLE); //旋轉進度條
                    m_btnCreateWF.setVisibility(View.GONE);
                    m_textVWTPrompt.setVisibility(View.GONE);
                    m_textVPromptAP.setText("正在創建熱點..."); //進度條文字
                    break;
                case WFOperateEnum.SEARCH:  //搜索可用熱點
                    //設置布局
                    m_textVWTPrompt.setVisibility(View.VISIBLE);
                    m_textVWTPrompt.setText("正在搜索附近的熱點...");
                    m_linearLCreateAP.setVisibility(View.GONE); //創建熱點布局不可用
                    m_btnCreateWF.setVisibility(View.VISIBLE);
                    m_btnCreateWF.setBackgroundResource(R.drawable.x_wt_create); //按鈕文字改回“創建”
                    m_gifRadar.setVisibility(View.GONE); //熱點動畫停止
                    m_linearLCreateAP.setVisibility(View.GONE); //下部創建熱點布局不可用
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
                    //搜索熱點線程關閉
                    if (m_createAPProcess.running)
                        m_createAPProcess.stop();
                    //關閉熱點
                    m_wiFiAdmin.createWifiAP(m_wiFiAdmin.createWifiInfo(m_wiFiAdmin.getApSSID(), WIFI_AP_PASSWORD, 3, "ap"),false);
                    //打開wifi
                    m_wiFiAdmin.OpenWifi();
                    m_wtSearchProcess.start();
                    m_FrameLWTSearchAnimation.startAnimation();
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
                    break;
                }
            }
        });
        //對話框取消按鈕事件
        m_btnCancelDialog.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //對話框布局消失
                m_LinearLDialog.setVisibility(View.GONE);
            }
        });
    }
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
    /**Wifi是否連接**/
    private boolean isWifiConnect() {
        boolean isConnect = true;
        //用于網絡連接狀態的檢測
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        if(!cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected())
            isConnect = false;
        return isConnect;
    }
    /**獲取wifi熱點狀態**/
    public boolean getWifiApState() {
        try {
            WifiManager localWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
            Method m = localWifiManager.getClass().getMethod("getWifiApState", new Class[0]);
            int i = (Integer)(m.invoke(localWifiManager, new Object[0]));
            return (3 == i) || (13 == i);  //WIFI_STATE_ENABLED 3  //WIFI_AP_STATE_ENABLED  13
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
    /**獲取手機信息**/
    public String getLocalHostName() {
        String str1 = Build.BRAND; //主板
        String str2 = Build.MODEL;  //機型
        if (-1 == str2.toUpperCase().indexOf(str1.toUpperCase()))
            str2 = str1 + "_" + str2;
        return str2;
    }
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
    private void init() {
        //線程是否在運行
        if(this.m_wtSearchProcess.running || this.m_createAPProcess.running) {
            return;
        }
        //沒有連接上wifi或者是wifi熱點
        if(!isWifiConnect() && !getWifiApState()) {
            m_wiFiAdmin.OpenWifi();
            m_wtSearchProcess.start(); //開啟搜索wifi超時檢測線程
            m_wiFiAdmin.startScan(); //開啟搜索wifi
            //開啟搜索動畫
            m_FrameLWTSearchAnimation.startAnimation();
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               
            //設置控件
            m_textVWTPrompt.setVisibility(View.VISIBLE);
            m_textVWTPrompt.setText(" 正在搜索附近的熱點...");
            m_linearLCreateAP.setVisibility(View.GONE);
            m_btnCreateWF.setBackgroundResource(R.drawable.x_wt_create);
        }
        //連接上wifi
        if(isWifiConnect()) {
            this.m_wiFiAdmin.startScan();
            this.m_wtSearchProcess.start();
            this.m_FrameLWTSearchAnimation.startAnimation();
            //設置控件
            this.m_textVWTPrompt.setVisibility(0);
            this.m_textVWTPrompt.setText("正在搜索附近的熱點...");
            this.m_linearLCreateAP.setVisibility(View.GONE);
            this.m_btnCreateWF.setBackgroundResource(R.drawable.x_wt_create);
            this.m_gifRadar.setVisibility(View.GONE);
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               
            m_listWifi.clear();
            if(m_wiFiAdmin.mWifiManager.getScanResults() != null) {
                for (int i = 0; i < m_wiFiAdmin.mWifiManager.getScanResults().size(); i++) {
                    //識別出自己自定連接的wifi
                    if(m_wiFiAdmin.mWifiManager.getScanResults().get(i).SSID.startsWith(WIFI_AP_HEADER)) {
                        m_listWifi.add(m_wiFiAdmin.mWifiManager.getScanResults().get(i)); //將指定wifi添加進去
                    }
                }
                m_wTAdapter.setData(m_listWifi); //將連接的信息添加到listView中
                m_wTAdapter.notifyDataSetChanged();
            }
            //連接上wifi熱點
            if(getWifiApState()){
                if(m_wiFiAdmin.getApSSID().startsWith(WIFI_AP_HEADER)) {
                    //設置控件
                    m_textVWTPrompt.setVisibility(View.GONE);
                    m_linearLCreateAP.setVisibility(View.VISIBLE);
                    m_progBarCreatingAP.setVisibility(View.GONE);
                    m_btnCreateWF.setVisibility(View.VISIBLE);
                    m_gifRadar.setVisibility(View.VISIBLE);
                    m_btnCreateWF.setBackgroundResource(R.drawable.x_ap_close);
                    m_textVPromptAP.setText("\n熱點名:"+ m_wiFiAdmin.getApSSID() + "\n連接密碼:zhf12345");
                }
            }
        }
    }
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        WIFIBroadcast.ehList.remove(this);
    }
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
    @Override
    public void handleConnectChange() {
        Message msg = mHandler.obtainMessage(m_nWTConnectResult);
        mHandler.sendMessage(msg);
    }
    @Override
    public void scanResultsAvaiable() {
        Message msg = mHandler.obtainMessage(m_nWTScanResult);
        mHandler.sendMessage(msg);
    }
    @Override
    public void wifiStatusNotification() {
        m_wiFiAdmin.mWifiManager.getWifiState(); //獲取當前wifi狀態
    }
}


貌似有點長。。。簡單說明一下:

   1.首先,初始化主界面(xml有些復雜,慢慢理一下就好了,不是什么大問題)接下來,處理三個重要的按鈕事件:右上角的搜索wifi按鈕、中間創建或關閉熱點按鈕、對話框中確定按鈕。處理前兩者事件時,需關注當前wifi狀態,若為占用,需彈出提醒對話框來根據當前WiFi操作(WFOperateEnum類中定義好了)事件,來創建、關閉、搜索等具體事務。

   2.之所以定義廣播接收者,是為了監聽當wifi狀態發生變化時,能夠及時更新界面


廣播接收者WIFIBroadcast類:

package com.zhf.wifidemo.broadcast;
import java.util.ArrayList;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.util.Log;
/**
 * 監聽wifi熱點變化
 * @author ZHF
 *
 */
public class WIFIBroadcast extends BroadcastReceiver{
    public static ArrayList<EventHandler> ehList = new ArrayList<EventHandler>();
                                                                                                                                                                                                                                                                                                                                                
    @Override
    public void onReceive(Context context, Intent intent) {
        //搜索到wifi熱點結果的廣播:  "android.net.wifi.SCAN_RESULTS"
        if(intent.getAction().endsWith(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
            Log.i("WTScanResults---->掃描到了可用網絡---->", "android.net.wifi.SCAN_RESULTS");
            //遍歷通知各個監聽接口
            for(int i = 0; i < ehList.size(); i++) {
                ((EventHandler)ehList.get(i)).scanResultsAvaiable();
            }
                                                                                                                                                                                                                                                                                                                                                        
        //wifi打開或關閉狀態變化   "android.net.wifi.WIFI_STATE_CHANGED"
        }else if(intent.getAction().endsWith(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
            Log.i("WTScanResults----->wifi狀態變化--->", "android.net.wifi.WIFI_STATE_CHANGED");
            //這里不需要連接一個SSID(wifi名稱)
            for(int j = 0; j < ehList.size(); j++) {
                ((EventHandler)ehList.get(j)).wifiStatusNotification();
            }
                                                                                                                                                                                                                                                                                                                                                        
        //連接上一個SSID后發出的廣播,(注:與android.net.wifi.WIFI_STATE_CHANGED的區別)
        }else if(intent.getAction().endsWith(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
            Log.i("WTScanResults----->網絡狀態變化---->", "android.net.wifi.STATE_CHANGE");
            for(int m = 0; m < ehList.size(); m++) {
                ((EventHandler)ehList.get(m)).handleConnectChange();
            }
        }
    }
    /**
     * 事件監聽接口
     * @author ZHF
     *
     */
    public static abstract interface EventHandler {
        /**處理連接變化事件**/
        public abstract void handleConnectChange();
        /**掃描結果是有效事件**/
        public abstract void scanResultsAvaiable();
        /**wifi狀態變化事件**/
        public abstract void wifiStatusNotification();
    }
                                                                                                                                                                                                                                                                                                                                                
}


說明:監聽系統wifi狀態變化,內部定義了一個事件處理接口,當wifi狀態發生變化時,讓其實現類去發送消息更新界面。


CreateAPProcess類:

package com.zhf.wifidemo.ui;
import android.net.wifi.WifiManager;
import android.os.Message;
import com.zhf.wifidemo.wifi.MainActivity;
/**
 * 創建Wifi熱點
 * @author ZHF
 *
 */
public class CreateAPProcess implements Runnable{
                                                                                                                                                                                             
    public MainActivity context;
                                                                                                                                                                                             
    public boolean running = false;
    private long startTime = 0L;
    private Thread thread = null;
    public CreateAPProcess(MainActivity context) {
        super();
        this.context = context;
    }
    @Override
    public void run() {
        while(true) {
            if(!running)  return;
            //WIFI_STATE_ENABLED 3
            //WIFI_AP_STATE_ENABLED  13
            if((context.m_wiFiAdmin.getWifiApState() == WifiManager.WIFI_STATE_ENABLED)
                    || (context.m_wiFiAdmin.getWifiApState() == 13)
                    || (System.currentTimeMillis() - this.startTime >= 30000L)){
                //wifi可用 或 熱點可用
                Message msg = context.mHandler.obtainMessage(context.m_nCreateAPResult);
                context.mHandler.sendMessage(msg);
            }
            try {
                Thread.sleep(5L);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
                                                                                                                                                                                                 
    }
                                                                                                                                                                                             
    public void start() {
        try {
            thread = new Thread(this);
            running = true;
            startTime = System.currentTimeMillis();
            thread.start(); //開啟線程
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
                                                                                                                                                                                             
    public void stop() {
        try {
            running = false;
            thread = null;
            startTime = 0L;
        } catch (Exception e) {
            // TODO: handle exception
        }
    }
}


其他類文件具體看源碼,當創建一個熱點成功后,等待其他客戶端搜索

上圖:

【移動開發】Android中WIFI開發總結(二)【移動開發】Android中WIFI開發總結(二)【移動開發】Android中WIFI開發總結(二)【移動開發】Android中WIFI開發總結(二)【移動開發】Android中WIFI開發總結(二)【移動開發】Android中WIFI開發總結(二)


WIFIAdapte類:

/**
 * 網絡列表適配器
 * @author ZHF
 *
 */
public class WTAdapter extends BaseAdapter {
    private LayoutInflater mInflater;
    private List<ScanResult> mList;  //掃描到的網絡結果列表
    private MainActivity mContext;
    public WTAdapter(MainActivity context, List<ScanResult> list) {
        // TODO Auto-generated constructor stub
        this.mContext = context;
        this.mList = list;
        this.mInflater = LayoutInflater.from(context);
    }
    //新加的一個函數,用來更新數據
    public void setData(List<ScanResult> list) {
        this.mList = list;
        notifyDataSetChanged();
    }
                                                                
    @Override
    public int getCount() {
        return mList.size();
    }
    @Override
    public Object getItem(int position) {
        return mList.get(position);
    }
    @Override
    public long getItemId(int position) {
        return position;
    }
    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        //獲取點擊向的掃描結果
        final ScanResult localScanResult = mList.get(position);
        //獲取wifi類
//      final WifiAdmin wifiAdmin = WifiAdmin.getInstance(mContext);
        final WifiAdmin wifiAdmin = mContext.m_wiFiAdmin;
        final ViewHolder viewHolder;
        if (convertView == null) {
            viewHolder = new ViewHolder();
            convertView = mInflater.inflate(R.layout.wtitem, null);
            //加載布局模板控件
            viewHolder.textVName = ((TextView) convertView.findViewById(R.id.name_text_wtitem));
            viewHolder.textConnect = ((TextView) convertView.findViewById(R.id.connect_text_wtitem));
            viewHolder.linearLConnectOk = ((LinearLayout) convertView.findViewById(R.id.connect_ok_layout_wtitem));
            viewHolder.progressBConnecting = ((ProgressBar) convertView.findViewById(R.id.connecting_progressBar_wtitem));
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        //點擊連接處理事件
        viewHolder.textConnect.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //創建wifi網絡
                WifiConfiguration localWifiConfiguration = wifiAdmin.createWifiInfo(localScanResult.SSID, MainActivity.WIFI_AP_PASSWORD, 3,"wt");
                //添加到網絡
                wifiAdmin.addNetwork(localWifiConfiguration);
                //"點擊鏈接"消失,顯示進度條,
                viewHolder.textConnect.setVisibility(View.GONE);
                viewHolder.progressBConnecting.setVisibility(View.VISIBLE);
                viewHolder.linearLConnectOk.setVisibility(View.GONE);
                //點擊后3.5s發送消息
                mContext.mHandler.sendEmptyMessageDelayed(mContext.m_nWTConnected, 3500L);
            }
        });
        // 點擊斷開處理事件
        viewHolder.linearLConnectOk.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //斷開指定wifi熱點
                wifiAdmin.disconnectWifi(wifiAdmin.getWifiInfo().getNetworkId());
                //"斷開連接"消失,進度條顯示
                viewHolder.textConnect.setVisibility(View.GONE);
                viewHolder.progressBConnecting.setVisibility(View.VISIBLE);
                viewHolder.linearLConnectOk.setVisibility(View.GONE);
                //點擊后3.5s發送消息
                mContext.mHandler.sendEmptyMessageDelayed(mContext.m_nWTConnected, 3500L);
            }
        });
        //初始化布局
        viewHolder.textConnect.setVisibility(View.GONE);
        viewHolder.progressBConnecting.setVisibility(View.GONE);
        viewHolder.linearLConnectOk.setVisibility(View.GONE);
        viewHolder.textVName.setText(localScanResult.SSID); //顯示熱點名稱
                                                                    
        // 正連接的wifi信息
        WifiInfo localWifiInfo = wifiAdmin.getWifiInfo();
        if (localWifiInfo != null) {
            try {//正在連接
                if ((localWifiInfo.getSSID() != null)&& (localWifiInfo.getSSID().equals(localScanResult.SSID))) {
                    viewHolder.linearLConnectOk.setVisibility(View.VISIBLE);
                    return convertView;
                }
            } catch (NullPointerException e) {
                e.printStackTrace();
                return convertView;
            }
            viewHolder.textConnect.setVisibility(View.VISIBLE);
        }
        return convertView;
    }
    public final class ViewHolder {
        public LinearLayout linearLConnectOk;
        public ProgressBar progressBConnecting;
        public TextView textConnect;
        public TextView textVName;
    }
}


   點擊連接,實現客戶連接,此時他們將處于同一網段內,接下來就可以自己實現傳輸數據,操控等一系列操作了。 在下一篇中我會繼實現一個基于wif熱點的多人聊天室,希望能幫助到大家!


源碼:http://down.51cto.com/data/1036876





向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

江源县| 双江| 信丰县| 华亭县| 佛冈县| 博罗县| 白山市| 九龙城区| 齐齐哈尔市| 获嘉县| 岢岚县| 吉木萨尔县| 和田市| 乐安县| 黑水县| 宿迁市| 安岳县| 兰坪| 农安县| 兴业县| 扶风县| 吴江市| 建阳市| 辰溪县| 陇西县| 丹凤县| 城步| 林周县| 康马县| 璧山县| 丰顺县| 平邑县| 庆元县| 海伦市| 吐鲁番市| 澄城县| 云霄县| 白城市| 南康市| 彰化市| 永康市|