Demo entry 6850843

后35

   

Submitted by anonymous on Jul 12, 2019 at 04:15
Language: Java. Code size: 56.7 kB.

package com.skyworth.show.settings.ui.wifi;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;

import com.skyworth.show.settings.R;
import com.skyworth.show.settings.base.BaseActivity;

public class WifiActivity extends BaseActivity {

    public static void home(Context context) {
        Intent intent = new Intent(context, WifiActivity.class);
        intent.putExtra("action", "home");
        context.startActivity(intent);
    }

    public static void info(Context context) {
        Intent intent = new Intent(context, WifiActivity.class);
        intent.putExtra("action", "info");
        context.startActivity(intent);
    }

    public static void connecting(Context context) {
        Intent intent = new Intent(context, WifiActivity.class);
        intent.putExtra("action", "connecting");
        context.startActivity(intent);
    }

    private String mAction;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wifi);

        parseIntent();

        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();

        ft.replace(R.id.content, new WifiHomeFragment());

        ft.commit();

//        requestPermissions();
    }

    private void parseIntent() {
        // 获取 getAction()
        mAction = getIntent().getAction();
        Log.i(TAG, "parseIntent 0: " + mAction);

        if (!TextUtils.isEmpty(mAction)) {
            // getAction() 不为空, 说明是隐式进来的
            // 解析 getAction()
            switch (mAction) {
                case "action0":
                case "action1":
                case "action2":
                    break;
                default:
                    break;
            }
        } else {
            // 如果 getAction() 为空, 说明是从 显示进来的
            mAction = getIntent().getStringExtra("action");
            Log.i(TAG, "parseIntent 1: " + mAction);
        }

        // 若果还为空, 就默认一个
        if (TextUtils.isEmpty(mAction)) {
            mAction = "home";
        }

        Log.i(TAG, "parseIntent 2: " + mAction);
    }

    /**
     * Android 6.0 之后需要定位权限才能接收到
     * 发现设备的广播
     * 包括蓝牙4.0 和 4.0之前
     */
    public void requestPermissions() {
        //判断是否已经赋予权限
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            //如果应用之前请求过此权限但用户拒绝了请求,此方法将返回 true。
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.ACCESS_COARSE_LOCATION)) {
                //这里可以写个对话框之类的项向用户解释为什么要申请权限,并在对话框的确认键后续再次申请权限
            } else {
                //申请权限,字符串数组内是一个或多个要申请的权限,1是申请权限结果的返回参数,在onRequestPermissionsResult可以得知申请结果
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,}, 1);
            }
        } else {
//            Log.i(TAG, "requestPermission: 有权限的");
        }
    }
}
package com.skyworth.show.settings.ui.wifi;

import android.net.wifi.WifiInfo;
import android.text.TextUtils;

import com.android.settingslib.wifi.AccessPoint;
import com.skyworth.show.settings.R;
import com.skyworth.show.settings.base.App;
import com.skyworth.show.settings.utils.NetUtils;

import java.util.Objects;

public class WiFiBean {

    private static final int RSSI_HIGH = -50;
    private static final int RSSI_LOW = -70;

    private WifiInfo mWifiInfo;
    private AccessPoint mAccessPoint;
    private String mSSID;

    public WiFiBean(WifiInfo wifiInfo) {
        mWifiInfo = wifiInfo;
        mSSID = wifiInfo.getSSID();
        if (!TextUtils.isEmpty(mSSID)) {
            if (mSSID.startsWith("\"") && mSSID.endsWith("\"")) {
                mSSID = mSSID.substring(1, mSSID.length() - 1);
            }
        }
    }

    public WiFiBean(AccessPoint accessPoint) {
        mAccessPoint = accessPoint;
        mSSID = accessPoint.getSsid().toString();
    }

    public WiFiBean() {
    }

    public AccessPoint getAccessPoint() {
        return mAccessPoint;
    }

    public WifiInfo getWifiInfo() {
        return mWifiInfo;
    }

    public int getIpAddress() {
        if (mWifiInfo != null) {
            return mWifiInfo.getIpAddress();
        }

        return 0;
    }

    public int getSecurity() {
        if (mAccessPoint != null) {
            return mAccessPoint.getSecurity();
        }

        if (mWifiInfo != null) {
            return NetUtils.getSecurity(App.getApp(), mWifiInfo);
        }

        return -1;
    }

    public int getNetworkId() {
        if (mAccessPoint != null) {
            if (mAccessPoint.getConfig() != null) {
                return mAccessPoint.getConfig().networkId;
            }
        }

        if (mWifiInfo != null) {
            return mWifiInfo.getNetworkId();
        }

        return -1;
    }

    public void clearConfig() {
        if (mAccessPoint != null) {
            mAccessPoint.clearConfig();
        }
    }

    public String getSSID() {
        return mSSID;
    }

    public int getRssi() {
        if (mAccessPoint != null) {
            return mAccessPoint.getRssi();
        }

        if (mWifiInfo != null) {
            return mWifiInfo.getRssi();
        }

        return 0;
    }

    /**
     * 获取信号强度等级
     * @return      3   高
     *              2   中
     *              1   低
     */
    public int getRssiLevel() {
        int rssi = getRssi();
        if (rssi > RSSI_HIGH) {
            return 3;
        } else if (rssi > RSSI_LOW) {
            return 2;
        } else {
            return 1;
        }
    }
}
package com.skyworth.show.settings.ui.wifi;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;

import com.skyworth.show.settings.R;
import com.skyworth.show.settings.base.BaseActivity;

public class WifiConnectingActivity extends BaseActivity {

    public static void start(Context context, String ssid, int security) {
        start(context, ssid, security, false, -1);
    }

    public static void start(Context context, String ssid, int security, boolean errorConnecting, int errorId) {
        Intent intent = new Intent(context, WifiConnectingActivity.class);
        intent.putExtra("ssid", ssid);
        intent.putExtra("security", security);
        intent.putExtra("errorConnecting", errorConnecting);
        intent.putExtra("errorId", errorId);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fragment_content);

        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();

        ft.replace(R.id.content, WifiConnectingFragment.getFragment(
                getIntent().getStringExtra("ssid"),
                getIntent().getIntExtra("security", 0),
                getIntent().getBooleanExtra("errorConnecting", false),
                getIntent().getIntExtra("errorId", -1)));

        ft.commit();
    }
}
package com.skyworth.show.settings.ui.wifi;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.NetworkInfo;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.skyworth.show.settings.C;
import com.skyworth.show.settings.R;
import com.skyworth.show.settings.base.App;
import com.skyworth.show.settings.base.BaseTitleFragment;
import com.skyworth.show.settings.utils.SToast;

/**
 * WiFi连接页面
 * <p>
 * 输入密码时, 保存密码
 */
public class WifiConnectingFragment extends BaseTitleFragment {

    public static WifiConnectingFragment getFragment(String ssid, int security) {
        return getFragment(ssid, security, false, -1);
    }

    public static WifiConnectingFragment getFragment(String ssid, int security, boolean errorConnecting, int errorId) {
        WifiConnectingFragment fragment = new WifiConnectingFragment();
        Bundle bundle = new Bundle();
        bundle.putString("ssid", ssid);
        bundle.putInt("security", security);
        bundle.putBoolean("errorConnecting", errorConnecting);
        bundle.putInt("errorId", errorId);
        fragment.setArguments(bundle);
        return fragment;
    }

    private TextView mTextSsid, mTextError;
    private TextView mTextConnect;
    private EditText mEditPwd;
    private ToggleButton mToggleButton;
    private LinearLayout mLinearSSID, mLinearConnect;
    private ImageView mImageRefresh;

    private String mSSID;
    private int mSecurity;
    private boolean mErrorConnecting;
    private int mErrorId = -1;

    /**
     * 是否连接失败
     */
    private boolean isDisconnected = false;

    private int mNetworkId = -1;

    /**
     * 是否正在连接
     */
    private boolean isConnecting = false;

    /**
     * 是否需要重试
     * 输入密码连接的需要
     * 密码变动后, 不需要
     */
//    private boolean needReconnect = false;

    private WifiManager mWifiManager;

    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
//            Log.i(TAG, "onReceive: " + intent.getAction());

            if (intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
                NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
                NetworkInfo.DetailedState state = info.getDetailedState();
                String ssid = info.getExtraInfo();
                if (ssid.startsWith("\"") && ssid.endsWith("\"")) {
                    ssid = ssid.substring(1, ssid.length() - 1);
                }

                Log.i(TAG, "网络状态改变: " + state + ", ssid: " + ssid);

//                if (state == NetworkInfo.DetailedState.CONNECTING) {
//                    showError("正在连接");
//                    startRefresh();
//                }

//                Log.i(TAG, "getExtraInfo: " + info.getExtraInfo());
                if (TextUtils.equals(ssid, mSSID)) {
                    Log.i(TAG, "连接的是我自己");
                } else {
                    Log.i(TAG, "连接别人了: " + ssid);

                    if (state == NetworkInfo.DetailedState.CONNECTED) {
//                        showError("已连接其他网络: " + ssid);
//                        stopRefresh();
                    }
                    return;
                }

                if (state == NetworkInfo.DetailedState.DISCONNECTED) {
                    isDisconnected = true;
                    isConnecting = false;

//                    if (!needReconnect) {
//                        mWifiManager.disconnect();
//                    }
                    mWifiManager.disconnect();
                    forget();
                    // 移除当前正在连接的 net id
                    App.getApp().putCache(C.cache.CACHE_CONNECTING_NET_ID, null);
                    App.getApp().putCache(C.cache.CACHE_CONNECTING_SSID, null);

                    showError("身份验证出现问题", true);
                    stopRefresh();
                } else if (state == NetworkInfo.DetailedState.CONNECTED) {
                    isDisconnected = false;
                    // 移除当前正在连接的 net id
                    App.getApp().putCache(C.cache.CACHE_CONNECTING_NET_ID, null);
                    App.getApp().putCache(C.cache.CACHE_CONNECTING_SSID, null);
                    SToast.show(R.string.connected);
                    finish();
                } else if (state == NetworkInfo.DetailedState.AUTHENTICATING) {
                    showError("正在验证身份...");
                } else if (state == NetworkInfo.DetailedState.FAILED) {
                    showError("连接失败");
                }
            }
        }
    };

    public WifiConnectingFragment() { }

    @Override
    protected int getSubLayoutResId() {
        return R.layout.fragment_wifi_connecting;
    }

    @Override
    protected void initView(View root) {
        mTextTitle.setText(R.string.input_pwd);

        mTextSsid = root.findViewById(R.id.text_ssid);
        mTextError = root.findViewById(R.id.text_pwd_error);
        mTextConnect = root.findViewById(R.id.button_connect);
        mEditPwd = root.findViewById(R.id.edit_pwd);
        mToggleButton = root.findViewById(R.id.toggle_pwd);
        mLinearSSID = root.findViewById(R.id.linear_ssid);
        mLinearConnect = root.findViewById(R.id.linear_connect);
        mImageRefresh = root.findViewById(R.id.image_refresh);

        if (getArguments() != null) {
            mSSID = getArguments().getString("ssid");
            mSecurity = getArguments().getInt("security");
            mErrorConnecting = getArguments().getBoolean("errorConnecting");
            mErrorId = getArguments().getInt("errorId", -1);

            Log.i(TAG, "initView: ==========================");
            Log.i(TAG, "mSSID: " + mSSID);
            Log.i(TAG, "mSecurity: " + mSecurity);
            Log.i(TAG, "mErrorConnecting: " + mErrorConnecting);
            Log.i(TAG, "mErrorId: " + mErrorId);
            Log.i(TAG, "initView: ==========================");

            if (!TextUtils.isEmpty(mSSID)) {
                mTextSsid.setText(mSSID);
            }

            if (mErrorConnecting) {
                showErrorAfterHide();
            }
        }

        mWifiManager = (WifiManager) getActivity().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
    }

    @Override
    protected void initData() {
        super.initData();

        IntentFilter filter = new IntentFilter();

        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);

        getContext().registerReceiver(mBroadcastReceiver, filter);
    }

    @Override
    protected void initListener() {
        mLinearConnect.setOnClickListener(this);

        mEditPwd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                hideError();
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mLinearConnect.setEnabled(mEditPwd.getText().length() >= 8);
                mTextConnect.setTextColor(mEditPwd.getText().length() >= 8 ?
                        getResources().getColor(R.color.button_enable) :
                        getResources().getColor(R.color.colorTextSecondary));

//                needReconnect = false;
            }
        });

        mToggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    mEditPwd.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                    mEditPwd.setTransformationMethod(null);
                    mEditPwd.setSelection(mEditPwd.getText().length());
                } else {
                    mEditPwd.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    mEditPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    mEditPwd.setSelection(mEditPwd.getText().length());
                }
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        getContext().unregisterReceiver(mBroadcastReceiver);

//        if (isDisconnected) {
//            forget();
//        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.toolbar_linear_left:
                finish();
                break;
            case R.id.linear_connect:
                attemptConnect();
                break;
        }
    }

    private Runnable hideErrorRun = new Runnable() {
        @Override
        public void run() {
            hideError();
        }
    };

    /**
     * 显示错误, 延迟一段时间后隐藏
     */
    private void showErrorAfterHide() {
        showError("身份验证出现问题", true);
        mTextError.removeCallbacks(hideErrorRun);
        mTextError.postDelayed(hideErrorRun, 2000);
    }

    private void showError(String msg) {
        showError(msg, false);
    }

    private void showError(String msg, boolean isError) {
        mLinearSSID.setVisibility(View.INVISIBLE);
        mTextError.setVisibility(View.VISIBLE);

        mTextError.setText(msg);

        if (isError) {
            mTextError.setTextColor(getResources().getColor(R.color.colorTextError));
        } else {
            mTextError.setTextColor(getResources().getColor(R.color.colorTextSecondary));
        }
    }

    private void hideError() {
        mLinearSSID.setVisibility(View.VISIBLE);
        mTextError.setVisibility(View.INVISIBLE);
    }

    private void stopRefresh() {
        mImageRefresh.post(new Runnable() {
            @Override
            public void run() {
                mImageRefresh.clearAnimation();
                mImageRefresh.setVisibility(View.GONE);
            }
        });
    }

    private void startRefresh() {
        mImageRefresh.post(new Runnable() {
            @Override
            public void run() {
                mImageRefresh.setVisibility(View.VISIBLE);
                mImageRefresh.startAnimation(AnimationUtils.loadAnimation(getContext(), R.anim.anim_refresh));
            }
        });
    }

    private void attemptConnect() {
        if (mEditPwd.getText().length() < 8) {
            return;
        }

        if (isConnecting) {
            return;
        }

//        needReconnect = true;

        startRefresh();
//        hideError();

        showError("开始连接");

        isConnecting = connect();
        Log.i(TAG, "attemptConnect: " + mNetworkId);
    }

    private boolean connect() {
        // 如果是连接错误进来的,
        // 那么要先移除之前的连接
        forget(mErrorId);

        WifiConfiguration config = WifiUtils.createWifiConfiguration(mSecurity, mSSID, mEditPwd.getText().toString(), "");
        mNetworkId = mWifiManager.addNetwork(config);

        App.getApp().putCache(C.cache.CACHE_CONNECTING_NET_ID, mNetworkId);
        App.getApp().putCache(C.cache.CACHE_CONNECTING_SSID, mSSID);

        return mWifiManager.enableNetwork(mNetworkId, true);
    }

    private void forget() {
        forget(mNetworkId);
    }

    private void forget(int id) {
        if (id == -1) {
            return;
        }
//        mWifiManager.disableNetwork(mNetworkId);
        mWifiManager.removeNetwork(id);
    }
}
package com.skyworth.show.settings.ui.wifi;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Rect;
import android.net.wifi.SupplicantState;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.HandlerThread;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.CompoundButton;
import android.os.Process;
import android.widget.ImageView;
import android.widget.ToggleButton;

import com.android.settingslib.wifi.AccessPoint;
import com.android.settingslib.wifi.WifiTracker;
import com.skyworth.show.settings.R;
import com.skyworth.show.settings.base.BaseTitleFragment;
import com.skyworth.show.settings.utils.DisplayUtil;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * WiFi 列表
 *
 * WiFi 自动连接策略:
 *      信号强度达到某个阈值内的按照优先级挨个连接
 *      如果范围内没有, 按照信号强度来
 *      优先级: 连接次数? 待定
 */
public class WifiHomeFragment extends BaseTitleFragment {

//    private Switch mSwitch;
    private ToggleButton mToggleButton;
    private RecyclerView mRecyclerView;
    private ImageView mImageRefresh;

    private WifiTracker mWifiTracker;
    private WifiManager mWifiManager;

    private HandlerThread mBgThread;

    private WifiListRecyclerAdapter mRecyclerAdapter;

    private WifiTracker.WifiListener mWifiListener = new WifiTracker.WifiListener() {
        @Override
        public void onWifiStateChanged(int i) {
            Log.i(TAG, "onWifiStateChanged: " + i);
            handleWifiStateChanged(i);
        }

        @Override
        public void onConnectedChanged() {
//            Log.i(TAG, "onConnectedChanged: " + mWifiTracker.isConnected());

            WifiInfo info = mWifiManager.getConnectionInfo();
            Log.i(TAG, "onConnectedChanged: " + info);

            if (mWifiTracker.isConnected()) {
                if (info == null) {
                    mRecyclerAdapter.removeConnected();
                } else if (info.getSupplicantState() != SupplicantState.DISCONNECTED){
                    // 忽略已连接的WiFi时
                    // WifiTracker 的连接状态没有立刻更新
                    // WifiInfo 是 DISCONNECTED, 但是 WifiTracker 是已连接
                    // 此时 WifiInfo 中的 SSID 是 <unknown ssid>
                    mRecyclerAdapter.setConnected(new WiFiBean(info));
                }
            } else {
                mRecyclerAdapter.removeConnected();
                mWifiTracker.forceScan();
            }

            if (info == null) {
                mRecyclerAdapter.setConnecting(null);
            } else {
                if (info.getSupplicantState() == SupplicantState.DISCONNECTED) {
                    WiFiBean bean = new WiFiBean(info);
                    mRecyclerAdapter.setConnectingError(bean.getSSID());
                }
            }
        }

        @Override
        public void onAccessPointsChanged() {
            Log.i(TAG, "onAccessPointsChanged: ");

            handleAccessPointsChanged();
        }
    };

    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.i(TAG, "onReceive: " + intent.getAction());
            String action = intent.getAction();

            if (TextUtils.isEmpty(action)) {
                return;
            }

            switch (action) {
                case WifiManager.WIFI_STATE_CHANGED_ACTION:
                    break;
                case WifiManager.SCAN_RESULTS_AVAILABLE_ACTION:
                    break;

            }
        }
    };

    private SwitchRunnable mSwitchRunnable;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mBgThread = new HandlerThread(TAG, Process.THREAD_PRIORITY_BACKGROUND);
        mBgThread.start();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        mWifiTracker = new WifiTracker(getActivity(), mWifiListener, mBgThread.getLooper(), true, true, true);

        mWifiManager = mWifiTracker.getManager();
    }

    @Override
    protected int getSubLayoutResId() {
        return R.layout.fragment_wifi_home;
    }

    @Override
    protected void initView(View root) {
        setTitle(R.string.wirelessNetwork);
//        mTextRight.setVisibility(View.VISIBLE);
//        mTextRight.setText(R.string.refresh);

        mRecyclerView = root.findViewById(R.id.wifi_home_recycler);
//        mSwitch = root.findViewById(R.id.wifi_home_switch);
        mToggleButton = root.findViewById(R.id.wifi_home_toggle);
        mImageRefresh = root.findViewById(R.id.image_refresh);

        mRecyclerView.setNestedScrollingEnabled(false);
        mRecyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                outRect.set(0, 0, 0, DisplayUtil.dip2Pix(1));
            }
        });

        register();
    }

    @Override
    protected void initData() {
        mSwitchRunnable = new SwitchRunnable(this);

        mRecyclerAdapter = new WifiListRecyclerAdapter();
        mRecyclerView.setAdapter(mRecyclerAdapter);
    }

    private void discovery() {
        mWifiTracker.forceScan();
    }

    @Override
    protected void initListener() {
        mToggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                mToggleButton.removeCallbacks(mSwitchRunnable);
                mSwitchRunnable.b = isChecked;
                if (isChecked) {
                    mImageRefresh.setVisibility(View.VISIBLE);
                    mImageRefresh.startAnimation(AnimationUtils.loadAnimation(getContext(), R.anim.anim_refresh));

                    mRecyclerView.setVisibility(View.VISIBLE);
                } else {
                    mImageRefresh.clearAnimation();
                    mImageRefresh.setVisibility(View.GONE);

                    mRecyclerView.setVisibility(View.INVISIBLE);
                }
                mToggleButton.postDelayed(mSwitchRunnable, 300);
            }
        });

        mRecyclerAdapter.setWiFiAdapterListener(new WifiListRecyclerAdapter.WiFiAdapterListener() {
            @Override
            public void onConnectedClick(WiFiBean bean) {
                showForgetDialog(bean);
            }

            @Override
            public void onWifiClick(WiFiBean bean) {
                // 已经保存过的, 或者无密码的, 直接连接
                if (bean.getAccessPoint().isSaved()) {
                    Log.i(TAG, "直接连接: " + bean.getNetworkId());
                    mRecyclerAdapter.setConnecting(bean.getSSID());
                    mWifiManager.enableNetwork(bean.getNetworkId(), true);
                } else if (bean.getSecurity() == AccessPoint.SECURITY_NONE) {
                    connect(bean);
                } else {
                    WifiConnectingActivity.start(getContext(), bean.getSSID(), bean.getSecurity());
                }
            }

            @Override
            public void onWifiLongClick(WiFiBean bean) {
                showForgetDialog(bean);
            }

            @Override
            public void onWifiConnectingError(WiFiBean bean) {
                WifiConnectingActivity.start(getContext(), bean.getSSID(), bean.getSecurity(), true, bean.getNetworkId());
            }
        });
    }

    @Override
    public void onStart() {
        super.onStart();

        mWifiTracker.startTracking();
    }

    @Override
    public void onResume() {
        super.onResume();

//        mWifiTracker.startTracking();
    }

    @Override
    public void onPause() {
        super.onPause();

//        mWifiTracker.stopTracking();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        if (getContext() != null) {
            getContext().unregisterReceiver(mBroadcastReceiver);
        }

        mWifiTracker.stopTracking();

        mToggleButton.removeCallbacks(mSwitchRunnable);
        mToggleButton.removeCallbacks(mRunnable);
        mBgThread.quit();
    }

    private boolean connect(WiFiBean bean) {
        WifiConfiguration config = WifiUtils.createWifiConfiguration(bean.getSecurity(), bean.getSSID(), "", "");
        int netWorkId = mWifiManager.addNetwork(config);
        return mWifiManager.enableNetwork(netWorkId, true);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.toolbar_linear_left:
                finish();
                break;
//            case R.id.toolbar_text_right_menu:
//                discovery();
//                break;
        }
    }

    private void showForgetDialog(final WiFiBean bean) {
        Log.i(TAG, "showForgetDialog: " + bean.getNetworkId());
        ForgetWifiDialog dialog = ForgetWifiDialog.getFragment(bean.getSSID(), String.valueOf(bean.getIpAddress()), bean.getNetworkId());
        dialog.show(getChildFragmentManager(), "forget");
        dialog.setOnForgetListener(new ForgetWifiDialog.onForgetListener() {
            @Override
            public void onForget(boolean isSuccess) {
                if (isSuccess) {
                    bean.clearConfig();
                }
            }
        });
    }

    /**
     * 注册 WiFi 广播
     */
    private void register() {
        if (getContext() != null) {
            IntentFilter filter = new IntentFilter();

            filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);            // wifi开关变化通知
            filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);        // wifi扫描结果通知
//          filter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);      // wifi连接结果通知
//          filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);         // 网络状态变化通知

            getContext().registerReceiver(mBroadcastReceiver, filter);
        }
    }

    private void handleAccessPointsChanged() {
        List<WiFiBean> list = new ArrayList<>();
        for (AccessPoint point : mWifiTracker.getAccessPoints()) {
            list.add(new WiFiBean(point));
        }

        List<WiFiBean> beanList = new ArrayList<>();

        // 添加间隔
        beanList.add(new WiFiBean());

        // 按照信号强度排序
//        Collections.sort(list, new Comparator<AccessPoint>() {
//            @Override
//            public int compare(AccessPoint o1, AccessPoint o2) {
//                return o2.getRssi() - o1.getRssi();
//            }
//        });
        Collections.sort(list, new Comparator<WiFiBean>() {
            @Override
            public int compare(WiFiBean o1, WiFiBean o2) {
                if (o1.getRssiLevel() != o2.getRssiLevel()) {
                    return o2.getRssiLevel() - o1.getRssiLevel();
                }

                return o2.getSSID().compareTo(o1.getSSID());
            }
        });

        // 添加列表
        beanList.addAll(list);
//        for (AccessPoint point : list) {
//            beanList.add(new WiFiBean(point));
//        }

        boolean hasAvailable = mRecyclerAdapter.setList(beanList);
        if (mImageRefresh.isShown() && !beanList.isEmpty() && hasAvailable) {
            mImageRefresh.clearAnimation();
            mImageRefresh.setVisibility(View.GONE);
        }
    }

    /**
     * 处理 WiFi 状态
     * @param state
     */
    private void handleWifiStateChanged(int state) {
        Log.i(TAG, "handleWifiStateChanged: " + state);
        switch (state) {
            case WifiManager.WIFI_STATE_ENABLING: // 2
                Log.i(TAG, "handleWifiStateChanged: WIFI_STATE_ENABLING");
//                mText.setText("正在打开");
//                mSwitch.setChecked(true);
                break;
            case WifiManager.WIFI_STATE_ENABLED: // 3
                Log.i(TAG, "handleWifiStateChanged: WIFI_STATE_ENABLED");
//                mText.setText("已打开");
                mRecyclerView.setVisibility(View.VISIBLE);
                mToggleButton.setChecked(true);
                enableSwitch(300);
                break;
            case WifiManager.WIFI_STATE_DISABLING: // 0
                Log.i(TAG, "handleWifiStateChanged: WIFI_STATE_DISABLING");
//                mText.setText("正在关闭");
//                mSwitch.setChecked(false);
                break;
            case WifiManager.WIFI_STATE_DISABLED: // 1
                Log.i(TAG, "handleWifiStateChanged: WIFI_STATE_DISABLED");
//                mText.setText("已关闭");
                mRecyclerAdapter.clear();
                mRecyclerView.setVisibility(View.GONE);
                mToggleButton.setChecked(false);
                enableSwitch(300);
                System.out.println("WifiSettings: enable");
                break;
            default:
                Log.i(TAG, "handleWifiStateChanged: " + state);
        }
    }

    private Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            mToggleButton.setEnabled(true);
        }
    };
    private void enableSwitch(long delay) {
        mToggleButton.removeCallbacks(mRunnable);
        mToggleButton.postDelayed(mRunnable, delay);
    }

    /**
     * WiFi 开关
     */
    private class SwitchRunnable implements Runnable {

        private WeakReference<WifiHomeFragment> mReference;

        public boolean b = false;

        public SwitchRunnable (WifiHomeFragment fragment) {
            mReference = new WeakReference<>(fragment);
        }

        @Override
        public void run() {
            if (mReference == null || mReference.get() == null) {
                return;
            }

            if (!b) {
                mRecyclerAdapter.clear();
            }

            mWifiManager.setWifiEnabled(b);
            switch (mWifiManager.getWifiState()) {
                case WifiManager.WIFI_STATE_DISABLED:
                case WifiManager.WIFI_STATE_DISABLING:
                    if (b) {
                        mToggleButton.setEnabled(false);
                    }
                    break;
                case WifiManager.WIFI_STATE_ENABLED:
                case WifiManager.WIFI_STATE_ENABLING:
                    if (!b) {
                        mToggleButton.setEnabled(false);
                    }
                    break;
            }
        }
    }
}

package com.skyworth.show.settings.ui.wifi;

import android.content.Context;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.skyworth.show.settings.R;
import com.skyworth.show.settings.base.BaseTitleFragment;

/**
 * WiFi 详情页面
 *
 * 点击忽略此网络按钮  删除数据
 */
public class WifiInfoFragment extends BaseTitleFragment {

    public static WifiInfoFragment getFragment(String ssid, String ip) {
        WifiInfoFragment fragment = new WifiInfoFragment();
        Bundle bundle = new Bundle();
        bundle.putString("ssid", ssid);
        bundle.putString("ip", ip);
        fragment.setArguments(bundle);
        return fragment;
    }

    private WifiManager mWifiManager;

    private String mIp;

    private TextView mTextIP;

    public WifiInfoFragment(){}

    @Override
    protected int getSubLayoutResId() {
        return R.layout.fragment_wifi_info;
    }

    @Override
    protected void initView(View root) {
        mTextIP = root.findViewById(R.id.text_ip_address);

        if (getArguments() != null) {
            String ssid = getArguments().getString("ssid");
            mIp = getArguments().getString("ip");

            try {
                int ipInt = Integer.parseInt(mIp);
                mTextIP.setText(intToIp(ipInt));
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }

            if (!TextUtils.isEmpty(ssid)) {
                mTextTitle.setText(ssid);
            }
        }

        mWifiManager = (WifiManager) getActivity().getApplicationContext().getSystemService(Context.WIFI_SERVICE);

        root.findViewById(R.id.button_forget).setOnClickListener(this);
    }

    public String intToIp(int i) {
        return ((i >> 24) & 0xFF) + "." + ((i >> 16) & 0xFF) + "."
                + ((i >> 8) & 0xFF) + "." + (i & 0xFF);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.toolbar_linear_left:
                finish();
                break;
            case R.id.button_forget:
                forget();
                break;
        }
    }

    private void forget() {
        try {
            int ipInt = Integer.parseInt(mIp);
            mWifiManager.disableNetwork(ipInt);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }
}
package com.skyworth.show.settings.ui.wifi;

import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;

import com.skyworth.show.settings.R;
import com.skyworth.show.settings.base.BaseRecyclerViewHolder;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class WifiListRecyclerAdapter extends RecyclerView.Adapter<BaseRecyclerViewHolder> {

    private static final int TYPE_NORMAL = 0;
    private static final int TYPE_GAP = 1;
    private static final int TYPE_CONNECTED = 2;
    private static final int TYPE_CONNECTING = 3;

    private List<WiFiBean> mList = new ArrayList<>();
    private WiFiBean mConnectedBean;
    private WiFiBean mConnectingBean;
    private String mConnectingSSID;

    private WiFiAdapterListener mWiFiAdapterListener;

    public WiFiAdapterListener getWiFiAdapterListener() {
        return mWiFiAdapterListener;
    }

    public void setWiFiAdapterListener(WiFiAdapterListener wiFiAdapterListener) {
        mWiFiAdapterListener = wiFiAdapterListener;
    }

    public interface WiFiAdapterListener {
        void onConnectedClick(WiFiBean bean);
        void onWifiClick(WiFiBean bean);
        void onWifiLongClick(WiFiBean bean);
        void onWifiConnectingError(WiFiBean bean);
    }

    /**
     * 设置 WiFi 列表
     * @param list  WiFi 列表
     * @return      true    有可以展示的数据
     *               false   没有可以展示的数据
     */
    public boolean setList(List<WiFiBean> list) {
        mList.clear();
        Map<String, WiFiBean> t = new LinkedHashMap<>();
        if (list != null) {
            for (WiFiBean bean : list) {
                // 过滤掉不在线的
                if (bean.getRssi() <= Integer.MIN_VALUE) {
//                    Log.i("6666666666", "setList: " + bean.getAccessPoint().isActive());
                    continue;
                }
                t.put(bean.getSSID(), bean);
            }
        }

        // TODO: 2018/8/24 当前连接的WiFi 不需要在列表中显示
        if (mConnectedBean != null) {
            t.remove(mConnectedBean.getSSID());
        }

        mList.addAll(t.values());

        notifyDataSetChanged();
        // 肯定有一个间隔, 所以要大于1
        return mList.size() > 1;
    }

    /**
     * 设置正在连接的 wifi
     */
    public void setConnecting(String ssid) {

        // 获取下标
        int index = getIndexBySSID(ssid);

        // 找到了
        if (index >= 0) {
            mConnectingSSID = ssid;
            notifyBean(ssid);
        } else {
            if (mConnectingSSID != null) {
                notifyBean(mConnectingSSID);
                mConnectingSSID = null;
                mConnectingBean = null;
            }
        }
    }

    /**
     * 连接失败
     * @param ssid
     */
    public void setConnectingError(String ssid) {

        if (TextUtils.equals(ssid, mConnectingSSID) && mConnectingBean != null) {
            if (mWiFiAdapterListener != null) {
                mWiFiAdapterListener.onWifiConnectingError(mConnectingBean);
            }
        }

        setConnecting(null);
    }

    private void notifyBean(WiFiBean bean) {
        int index = mList.indexOf(bean);
        if (index >= 0) {
            notifyItemChanged(index);
        }
    }

    private void notifyBean(String ssid) {
        int index = getIndexBySSID(ssid);
        if (index >= 0) {
//            notifyItemChanged(index);
            notifyDataSetChanged();
        }
    }

    private int getIndexBySSID(String ssid) {
        if (TextUtils.isEmpty(ssid)) {
            return -1;
        }

        for (int i = 0, len = mList.size(); i < len; i++) {
            if (TextUtils.equals(ssid, mList.get(i).getSSID())) {
                return i;
            }
        }
        return -1;
    }

    private WiFiBean getWiFiBeanBySSID(String ssid) {
        if (TextUtils.isEmpty(ssid)) {
            return null;
        }

        for (WiFiBean bean : mList) {
            if (TextUtils.equals(ssid, bean.getSSID())) {
                return bean;
            }
        }
        return null;
    }

    /**
     * 设置 连接的 Wifi bean
     */
    public void setConnected(WiFiBean connectedBean) {
        if (connectedBean == null) {
            removeConnected();
            return;
        }

        // 是否已连接
        // true:  表示之前已连接, 需要 更新   第一个
        // false: 表示之前未连接, 需要 insert 第一个
        boolean isConnected = (mConnectedBean != null);

        mConnectedBean = connectedBean;

        if (isConnected) {
//            notifyItemChanged(0);
        } else {
//            notifyItemInserted(0);
        }

        if (mConnectingSSID != null) {
            notifyBean(mConnectingSSID);
            mConnectingSSID = null;
            mConnectingBean = null;
        }

        notifyDataSetChanged();
    }

    public void removeConnected() {
        if (mConnectedBean != null) {
            mConnectedBean = null;
//            notifyItemRemoved(0);
            notifyDataSetChanged();
        }
    }

    public void clear() {
        mList.clear();
        mConnectedBean = null;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public BaseRecyclerViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        if (i == TYPE_GAP) {
            View item = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_recycler_gap, viewGroup, false);
            return new GapViewHolder(item);
        }
        if (i == TYPE_CONNECTED) {
            View item = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_recycler_wifi, viewGroup, false);
            return new ConnectedViewHolder(item);
        }
        if (i == TYPE_CONNECTING) {
            View item = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_recycler_wifi, viewGroup, false);
            return new ConnectingViewHolder(item);
        }

        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_recycler_wifi, viewGroup, false);
        return new WifiViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull BaseRecyclerViewHolder baseRecyclerViewHolder, int i) {
        if (mConnectedBean != null) {
            i--;
        }
        baseRecyclerViewHolder.setData(i);
    }

    @Override
    public int getItemCount() {
        // 列表长度 + 已连接的
        return (mList == null ? 0 : mList.size()) + (mConnectedBean == null ? 0 : 1);
    }

    @Override
    public void onViewRecycled(@NonNull BaseRecyclerViewHolder holder) {
        super.onViewRecycled(holder);

        if (holder instanceof ConnectingViewHolder) {
            ((ConnectingViewHolder) holder).stopRefresh();
        }
    }

    @Override
    public int getItemViewType(int position) {
        // 不为空
        if (mConnectedBean != null) {
            if (position == 0) {
                return TYPE_CONNECTED;
            } else {
                position--;
            }
        }

        WiFiBean bean = mList.get(position);
        if (bean.getAccessPoint() != null) {

            if (TextUtils.equals(mConnectingSSID, bean.getSSID())) {
                return TYPE_CONNECTING;
            }

            return TYPE_NORMAL;
        }

        if (bean.getWifiInfo() != null) {
            return TYPE_CONNECTED;
        }

        return TYPE_GAP;
    }

    /**
     * 普通 ViewHolder
     */
    class WifiViewHolder extends BaseRecyclerViewHolder {

        private TextView mTextView;
        private ImageView mImageLock, mImageGot, mImageIcon;

        public WifiViewHolder(@NonNull View itemView) {
            super(itemView);

            mTextView = itemView.findViewById(R.id.text_wifi_name);
            mImageGot = itemView.findViewById(R.id.image_wifi_got);
            mImageLock = itemView.findViewById(R.id.image_wifi_lock);
            mImageIcon = itemView.findViewById(R.id.image_wifi_icon);
        }

        @Override
        public void setData(final int position) {
            final WiFiBean bean = mList.get(position);
            mTextView.setText(bean.getSSID());

            int security = 2;
            try {
                security = bean.getSecurity();
            } catch (Exception e) {
                e.printStackTrace();
            }
            mImageLock.setVisibility(security == 0 ? View.GONE : View.VISIBLE);

            mImageIcon.setImageLevel(bean.getRssiLevel());

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mWiFiAdapterListener != null) {
                        mWiFiAdapterListener.onWifiClick(bean);
                    }
                }
            });

            itemView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    if (bean.getAccessPoint().isSaved()) {
                        if (mWiFiAdapterListener != null) {
                            mWiFiAdapterListener.onWifiLongClick(bean);
                        }
                        return true;
                    }
                    return false;
                }
            });
        }
    }

    /**
     * 正在连接
     */
    class ConnectingViewHolder extends BaseRecyclerViewHolder {

        private TextView mTextView;
        private ImageView mImageRefresh, mImageGot, mImageLock, mImageIcon;

        public ConnectingViewHolder(@NonNull View itemView) {
            super(itemView);

            mTextView = itemView.findViewById(R.id.text_wifi_name);
            mImageGot = itemView.findViewById(R.id.image_wifi_got);
            mImageRefresh = itemView.findViewById(R.id.image_wifi_refresh);
            mImageLock = itemView.findViewById(R.id.image_wifi_lock);
            mImageIcon = itemView.findViewById(R.id.image_wifi_icon);
        }

        @Override
        public void setData(int position) {
            final WiFiBean bean = mList.get(position);
            mConnectingBean = bean;

            mTextView.setText(bean.getSSID());
            mImageRefresh.setVisibility(View.VISIBLE);

            int security = 2;
            try {
                security = bean.getSecurity();
            } catch (Exception e) {
                e.printStackTrace();
            }
            mImageLock.setVisibility(security == 0 ? View.GONE : View.VISIBLE);

            mImageIcon.setImageLevel(bean.getRssiLevel());

            startRefresh();
        }

        private void stopRefresh() {
            mImageRefresh.post(new Runnable() {
                @Override
                public void run() {
                    mImageRefresh.clearAnimation();
                    mImageRefresh.setVisibility(View.GONE);
                }
            });
        }

        private void startRefresh() {
            mImageRefresh.post(new Runnable() {
                @Override
                public void run() {
                    mImageRefresh.setVisibility(View.VISIBLE);
                    mImageRefresh.startAnimation(AnimationUtils.loadAnimation(itemView.getContext(), R.anim.anim_refresh));
                }
            });
        }
    }

    /**
     * 已连接的
     */
    class ConnectedViewHolder extends BaseRecyclerViewHolder {

        private TextView mTextView;
        private ImageView mImageLock, mImageGot, mImageIcon;

        public ConnectedViewHolder(@NonNull View itemView) {
            super(itemView);

            mTextView = itemView.findViewById(R.id.text_wifi_name);
            mImageGot = itemView.findViewById(R.id.image_wifi_got);
            mImageLock = itemView.findViewById(R.id.image_wifi_lock);
            mImageIcon = itemView.findViewById(R.id.image_wifi_icon);
        }

        @Override
        public void setData(int position) {
            final WiFiBean bean = mConnectedBean;
            mTextView.setText(bean.getSSID());
            mImageGot.setVisibility(View.VISIBLE);

            int security = 2;
            try {
                security = bean.getSecurity();
            } catch (Exception e) {
                e.printStackTrace();
            }
            mImageLock.setVisibility(security == 0 ? View.GONE : View.VISIBLE);

            mImageIcon.setImageLevel(bean.getRssiLevel());

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
//                    WifiInfoActivity.start(v.getContext(), bean.getSSID(), "" + bean.getWifiInfo().getIpAddress());
                    if (mWiFiAdapterListener != null) {
                        mWiFiAdapterListener.onConnectedClick(bean);
                    }
                }
            });
        }
    }

    class GapViewHolder extends BaseRecyclerViewHolder {

        public GapViewHolder(@NonNull View itemView) {
            super(itemView);
        }

        @Override
        public void setData(int position) {

        }
    }
}
package com.skyworth.show.settings.ui.wifi;

import com.android.settingslib.wifi.AccessPoint;
//import com.android.settingslib.wifi.WifiAdapter;

import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiEnterpriseConfig;
import android.os.Build;
import android.widget.TextView;

public class WifiUtils {

    public static boolean passwordIsValid(TextView passwordView, int accessPointSecurity) {
        if (passwordView == null) {
            return false;
        }

        switch (accessPointSecurity) {
            case AccessPoint.SECURITY_WEP:
                return isWepKeyValid(passwordView.getText().toString());
            case AccessPoint.SECURITY_PSK:
                return passwordView.length() >= 8;
            default:
                return true;
        }
    }

    public static WifiConfiguration createWifiConfiguration(AccessPoint accessPoint,
                                                            String password,
                                                            String userName) {

        WifiConfiguration config = createWifiConfiguration(accessPoint.getSecurity(),
                AccessPoint.convertToQuotedString(accessPoint.getSsidStr()), password, userName);

        config.hiddenSSID = false;

        return config;

    }

    public static WifiConfiguration createWifiConfiguration(int securityMode,
                                                            String ssid,
                                                            String password,
                                                            String userName) {
        WifiConfiguration config = new WifiConfiguration();
        config.hiddenSSID = true;
        config.SSID = ssid;
//        WifiAdapter.setWifiConfigurationShared(config, false);

        switch (securityMode) {
            case AccessPoint.SECURITY_NONE:
                config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
                break;
            case AccessPoint.SECURITY_WEP:
                config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
                config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
                config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
                int length = password.length();
                // WEP-40, WEP-104, and 256-bit WEP (WEP-232?)
                if ((length == 10 || length == 26 || length == 58)
                        && password.matches("[0-9A-Fa-f]*")) {
                    config.wepKeys[0] = password;
                } else {
                    config.wepKeys[0] = '"' + password + '"';
                }
                break;

            case AccessPoint.SECURITY_PSK:
                config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
                if (password.matches("[0-9A-Fa-f]{64}")) {
                    config.preSharedKey = password;
                } else {
                    config.preSharedKey = '"' + password + '"';
                }
                break;
            case AccessPoint.SECURITY_EAP: // only support PEAP
                config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
                config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.IEEE8021X);
                config.enterpriseConfig = new WifiEnterpriseConfig();

                config.enterpriseConfig.setEapMethod(WifiEnterpriseConfig.Eap.PEAP);
                config.enterpriseConfig.setPhase2Method(WifiEnterpriseConfig.Phase2.NONE);

//                config.enterpriseConfig.setFieldValue(WifiEnterpriseConfig.CA_CERT_KEY, null,
//                        WifiEnterpriseConfig.CA_CERT_PREFIX);
//                config.enterpriseConfig.setFieldValue("ca_path", null);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    config.enterpriseConfig.setDomainSuffixMatch("");
                }

//                config.enterpriseConfig.setClientCertificateAlias("");

                config.enterpriseConfig.setIdentity(userName);
                config.enterpriseConfig.setAnonymousIdentity("");

                config.enterpriseConfig.setPassword(password);
            default:
                break;
        }

        return config;
    }

    private static boolean isWepKeyValid(String password) {
        if (password == null || password.length() == 0) {
            return false;
        }
        int keyLength = password.length();
        /// M: ALPS03001760, confirmed by wap_supplicant, we don't support WEP-152 AP
        if (((keyLength == 10 || keyLength == 26) && password
                .matches("[0-9A-Fa-f]*"))
                || (keyLength == 5 || keyLength == 13)) {
            return true;
        }
        return false;
    }
}

This snippet took 0.08 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).