其他分享
首页 > 其他分享> > Android wifi开启扫描连接

Android wifi开启扫描连接

作者:互联网

1.开关按钮UI(switch_bluetooth)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="@dimen/item_hight"
    android:gravity="center_vertical"
    android:orientation="horizontal">

//开关按钮
    <Switch
        android:track="@drawable/switch_selector"
        android:thumb="@drawable/selector_thumb_check"
        android:id="@+id/swtich"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />


</LinearLayout>

2.wifi utils(WifiUtil)

public class WifiUtil {

    private final WifiManager mWifiManager;
    private final WifiInfo mWifiInfo;
    private static WifiUtil wifiUtil;
    private List<WifiConfiguration> mWifiConfiguration;
    public Context mcontext;
    private final ConnectivityManager mConnectivityManager;
    public static final int INVALID_NET_ID = -1;
    private static final Pattern HEX_PATTERN = Pattern.compile("^[0-9A-F]+$");

    private WifiUtil(Context context) {
        mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        mWifiInfo = mWifiManager.getConnectionInfo();
        mcontext = context;
        mConnectivityManager = (ConnectivityManager) context.getSystemService(
                Context.CONNECTIVITY_SERVICE);
    }

    public static WifiUtil getInstance(Context context) {
        if (wifiUtil == null) {
            wifiUtil = new WifiUtil(context);
        }
        return wifiUtil;
    }

    //open wifi
    public void openWiFi() {
        if (!isWifiEnable() && null != mWifiManager) {
            mWifiManager.setWifiEnabled(true);
        }
    }

    //close wifi
    public void closeWiFi() {
        if (isWifiEnable() && null != mWifiManager) {
            mWifiManager.setWifiEnabled(false);
        }
    }

    public boolean isWifiEnable() {
        return mWifiManager.isWifiEnabled();
    }

    @SuppressLint("MissingPermission")
    public List<WifiConfiguration> getLocalWifi() {
        mWifiConfiguration = mWifiManager.getConfiguredNetworks();
        return mWifiConfiguration;
    }

    //connect local wifi
    public void connectConfiguration(WifiConfiguration wifiConfiguration) {
        mWifiManager.enableNetwork(wifiConfiguration.networkId, true);
    }

    public void startScan() {
        if (null != mWifiManager) {
            mWifiManager.startScan();
        }
    }

    public List<ScanResult> getScanResults() {
        if (null != mWifiManager) {
            return mWifiManager.getScanResults();
        }
        return null;
    }

    //wifihot  isopen
    public boolean isApOn() {
        WifiManager wifimanager = (WifiManager) mcontext.getSystemService(mcontext.WIFI_SERVICE);
        try {
            Method method = wifimanager.getClass().getDeclaredMethod("isWifiApEnabled");
            method.setAccessible(true);
            return (Boolean) method.invoke(wifimanager);
        } catch (Throwable ignored) {
        }
        return false;
    }

}

3.开关按钮java(WifiSwitchView)

public class WifiSwitchView extends LinearLayout {

    private final Switch swtich;
    public WifiSwitchView(Context paramContext, AttributeSet paramAttributeSet) {
        super(paramContext, paramAttributeSet);
        View view = View.inflate(paramContext, R.layout.switch_bluetooth, this);
    
        swtich = view.findViewById(R.id.swtich);

        if (WifiUtil.getInstance(getContext()).isWifiEnable()) {
            swtich.setChecked(true);
        } else {
            swtich.setChecked(false);
        }

        swtich.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (swtich.isChecked()) {
                    WifiUtil.getInstance(getContext()).openWiFi();
                    Toast.makeText(paramContext, "开启wifi", Toast.LENGTH_SHORT).show();

                } else {
                    WifiUtil.getInstance(getContext()).closeWiFi();
                    Toast.makeText(paramContext, "关闭wifi", Toast.LENGTH_SHORT).show();

                }
            }
        });
    }4

4.扫描按钮UI(drop_down_more)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/bluetooth_ll_retrivel"
    android:layout_width="@dimen/item_short_width"
    android:layout_height="@dimen/item_short_hight"
    android:background="@drawable/round_light"
    android:paddingLeft="@dimen/padding_start"
    android:paddingRight="@dimen/padding_start"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/bluetooth_tv_retrivel"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_gravity="center"
        android:layout_weight="1"
        android:text="@string/bluetooth_equipment_retrivel"
        android:textSize="@dimen/middle_title"
        android:gravity="center_vertical"
        android:textColor="@color/text_dark" />


</LinearLayout>   

5.弹框显示扫描UI  (pop_wifiwindow)

<?xml version="1.0" encoding="utf-8"?>
<androidx.recyclerview.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:id="@+id/wifi_rl"
    android:background="#ffffff"
    android:layout_height="400dp">

</androidx.recyclerview.widget.RecyclerView>

6.弹框显示扫描itemUI(pop_wifirecy_item)

<?xml version="1.0" encoding="utf-8"?>
<androidx.recyclerview.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:id="@+id/wifi_rl"
    android:background="#ffffff"
    android:layout_height="400dp">

</androidx.recyclerview.widget.RecyclerView>

7.wifi适配器(WifiRecyclerAdapter)

package com.example.baoya.adapter;

import android.content.Context;
import android.net.wifi.ScanResult;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.baoya.R;
import java.util.List;

public class WifiRecyclerAdapter extends RecyclerView.Adapter<WifiRecyclerAdapter.ViewHolder>{
    Context context;
    List<ScanResult> scanResults;
    public WifiRecyclerAdapter(Context context, List<ScanResult> scanResults) {
        this.context=context;
        this.scanResults =scanResults;
    }

    @NonNull
    @Override
    public WifiRecyclerAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new ViewHolder(LayoutInflater.from(context).inflate(R.layout.pop_wifirecy_item,parent,false));
    }

    @Override
    public void onBindViewHolder(@NonNull WifiRecyclerAdapter.ViewHolder holder, final int position) {
        holder.wifi_name.setText(scanResults.get(position).SSID);
        holder.wifi_recy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (itemOnClick!=null){
                    itemOnClick.Success(position,scanResults.get(position).SSID);
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return scanResults==null?0:scanResults.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        TextView wifi_name;
        RelativeLayout wifi_recy;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            wifi_recy = itemView.findViewById(R.id.wifi_recy);
            wifi_name = itemView.findViewById(R.id.wifi_name);
        }
    }

    public interface ItemOnClick{
        void Success(int position,String ssid);
    }


    ItemOnClick itemOnClick;


    public void setItemOnClick(ItemOnClick itemOnClick){
        this.itemOnClick=itemOnClick;
    }




}

8.扫描显示java(WifiDeviceListView)

public class WifiDeviceListView extends LinearLayout {
    private final LinearLayout bluetooth_ll_retrivel;
    private PopupWindow popupWindow;
    private final WifiManager mWifiManager;
    private List<ScanResult> scanResults;
    private List<ScanResult> arrlist;
    private RecyclerView mWifi_rl;
    private EditText mEd_password;
    private WifiRecyclerAdapter wifiRecyclerAdapter;

    public WifiDeviceListView(Context paramContext, AttributeSet paramAttributeSet) {
        super(paramContext, paramAttributeSet);
        //设备搜索页面
        View view = View.inflate(paramContext, R.layout.drop_down_more, this);
        bluetooth_ll_retrivel = view.findViewById(R.id.bluetooth_ll_retrivel);
        //wifimanager
        mWifiManager = (WifiManager) paramContext.getSystemService(WIFI_SERVICE);
        //点击搜索
        bluetooth_ll_retrivel.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mWifiManager.isWifiEnabled()){
                    WifiUtil.getInstance(getContext()).startScan();
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                Thread.sleep(2000);
                                if (mWifiManager.getWifiState()==WifiManager.WIFI_STATE_ENABLED){
                                    mWifiManager.startScan();
                                }
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();
                }else{
                    if (arrlist!=null){
                        arrlist.clear();
                    }
                    Toast.makeText(paramContext, "先打开wifi", Toast.LENGTH_SHORT).show();
                }
                //弹窗
                popwindow();
            }
        });
    }
    //广播
    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)){
                scanResults = mWifiManager.getScanResults();
                Collections.sort(scanResults, new Comparator<ScanResult>() {
                    @Override
                    public int compare(ScanResult o1, ScanResult o2) {
                        return o2.level-o1.level;
                    }
                });
                Log.i("TAG", scanResults.toString());
                if (scanResults != null) {
                    if (arrlist !=null){
                        arrlist.clear();
                    }
//判断名称不能为空和重复
                    for (int i = 0; i < scanResults.size(); i++) {
                        if ((!scanResults.get(i).SSID.equals("")||!scanResults.get(i).SSID.isEmpty())){
                            arrlist.add(scanResults.get(i));
                            for (int j = 0; j <arrlist.size()-1 ; j++) {
                                for (int k = arrlist.size()-1; k >j ; k--) {
                                    if (arrlist.get(j).SSID.equals(arrlist.get(k).SSID)){
                                        arrlist.remove(arrlist.get(j));
                                    }
                                }
                            }
                        }
                    }
                    wifiRecyclerAdapter.notifyDataSetChanged();
                }
            }
        }
    };

    public void popwindow() {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.pop_wifiwindow, null);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        intentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
        getContext().registerReceiver(broadcastReceiver,intentFilter);
        popupWindow = new PopupWindow(view);
        popupWindow.setFocusable(true);
        Rect rect1 = new Rect();
        arrlist=new ArrayList<>();
        bluetooth_ll_retrivel.getWindowVisibleDisplayFrame(rect1);
        mWifi_rl = view.findViewById(R.id.wifi_rl);
        mWifi_rl.setLayoutManager(new LinearLayoutManager(getContext(),RecyclerView.VERTICAL,false));
        Rect rect2 = new Rect();
        bluetooth_ll_retrivel.getGlobalVisibleRect(rect2);


        wifiRecyclerAdapter = new WifiRecyclerAdapter(getContext(), arrlist);
        mWifi_rl.setAdapter(wifiRecyclerAdapter);

        popupWindow.setWidth(bluetooth_ll_retrivel.getWidth());
        popupWindow.setHeight(rect1.bottom - rect2.bottom);

        popupWindow.showAsDropDown(bluetooth_ll_retrivel);

        wifiRecyclerAdapter.setItemOnClick(new WifiRecyclerAdapter.ItemOnClick() {
            @Override
            public void Success(int position, String ssid) {
//点击连接wifi
                showPopupWindow(ssid);
            }
        });
    }

    public void showPopupWindow(final String ssid){
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        final View inflate = LayoutInflater.from(getContext()).inflate(R.layout.pop_wifi_connection, null);
        builder.setView(inflate);
        builder.setTitle(ssid);
        builder.setPositiveButton("连接", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                mEd_password = inflate.findViewById(R.id.ed_password);
                String password = mEd_password.getText().toString();
                connectWifiPws(ssid,password);
                Toast.makeText(getContext(), "正在连接", Toast.LENGTH_SHORT).show();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                Toast.makeText(getContext(), "取消连接", Toast.LENGTH_SHORT).show();
            }
        });
        builder.setCancelable(false);
        builder.show();
    }


    /**
     * 有密码连接
     * @param ssid
     * @param pws
     */
    public void connectWifiPws(String ssid, String pws){
        mWifiManager.disableNetwork(mWifiManager.getConnectionInfo().getNetworkId());
        int netId = mWifiManager.addNetwork(getWifiConfig(ssid, pws, true));
        mWifiManager.enableNetwork(netId, true);
    }

    /**
     * 无密码连接
     * @param ssid
     */
    public void connectWifiNoPws(String ssid){
        mWifiManager.disableNetwork(mWifiManager.getConnectionInfo().getNetworkId());
        int netId = mWifiManager.addNetwork(getWifiConfig(ssid, "", false));
        mWifiManager.enableNetwork(netId, true);
    }

    /**
     * wifi设置
     * @param ssid
     * @param pws
     * @param isHasPws
     */
    private WifiConfiguration getWifiConfig(String ssid, String pws, boolean isHasPws){
        WifiConfiguration config = new WifiConfiguration();
        config.allowedAuthAlgorithms.clear();
        config.allowedGroupCiphers.clear();
        config.allowedKeyManagement.clear();
        config.allowedPairwiseCiphers.clear();
        config.allowedProtocols.clear();
        config.SSID = "\"" + ssid + "\"";

        WifiConfiguration tempConfig = isExist(ssid);
        if(tempConfig != null) {
            mWifiManager.removeNetwork(tempConfig.networkId);
        }
        if (isHasPws){
            config.preSharedKey = "\""+pws+"\"";
            config.hiddenSSID = true;
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
            config.status = WifiConfiguration.Status.ENABLED;
        }else {
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        }
        return config;
    }

    /**
     * 得到配置好的网络连接
     * @param ssid
     * @return
     */
    private WifiConfiguration isExist(String ssid) {
        @SuppressLint("MissingPermission") List<WifiConfiguration> configs = mWifiManager.getConfiguredNetworks();
        for (WifiConfiguration config : configs) {
            if (config.SSID.equals("\""+ssid+"\"")) {
                return config;
            }
        }
        return null;
    }

9.连接wifiUI(pop_wifi_connection)

2.wifi utils(WifiUtil)2.wifi utils(WifiUtil)2.wifi utils(WifiUtil)2.wifi utils(WifiUtil)ee

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="50dp">

    <TextView
        android:id="@+id/pwss_word"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="输入密码:"
        android:layout_marginLeft="15dp"
        android:layout_centerVertical="true"
        >
    </TextView>

    <EditText
        android:id="@+id/ed_password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/pwss_word"
        android:layout_centerVertical="true"
        >
    </EditText>

</RelativeLayout>

10.wifi连接监听器:连接上及时刷新SSID

//WiFi连接监听注册
IntentFilter wifiConnection = new IntentFilter();
wifiConnection.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
wifiConnection.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
getContext().registerReceiver(new WifiConnectionReceiver(),wifiConnection);
class WifiConnectionReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        //wifi连接上与否
        if (intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
            NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
            if (info.getState().equals(NetworkInfo.State.CONNECTED)) {
                WifiManager wifiManager = (WifiManager) getActivity().getSystemService(WIFI_SERVICE);
                            WifiInfo connectionInfo = wifiManager.getConnectionInfo();
                                if (connectionInfo.getSSID()!=null) {
                                    editText.setText(connectionInfo.getSSID());
                                }
            }else if (info.getState().equals(NetworkInfo.State.DISCONNECTED)){
                                editText.setText("设备名称");
            }
        }
    }
}

标签:void,wifi,扫描,mWifiManager,new,Android,config,public
来源: https://blog.csdn.net/m0_58902390/article/details/119003335