Android 开发 创建WiFi、WiFi热点、蓝牙——操作集合

WIFI

权限

    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

 打开关闭WiFi、添加WiFi账号密码

/**
         * 返回WiFi状态
         * @param context 外部上下文
         * @return true=打开 false=关闭
         */
        public  boolean isWiFiActive(Context context){
            WifiManager wifimanager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);//得到wifi管理器对象

            return wifimanager.isWifiEnabled();
        }
        /**
         * 打开或者关闭WiFi
         * @param context 外部上下文
         * @param isOpen true=打开 false=关闭
         */
        public  void isOpenWifi(Context context,boolean isOpen) {
            WifiManager wifimanager  = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);//得到wifi管理器对象
            wifimanager.setWifiEnabled(isOpen); //打开或关闭
        }

        /**
         * 添加WiFi
         * @param context 外部上下文
         * @param wifiname WiFi账号
         * @param pwd WiFi密码
         */
        public  void AddWifiConfig(Context context, String wifiname , String pwd) {
            WifiManager wifimanager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);//得到wifi管理器对象
            int wifiId = -1;//自己定义的数值,判断用
            WifiConfiguration wifiCong = new WifiConfiguration();//这个类是我们构造wifi对象使用的,具体可以百度
            wifiCong.SSID = "\"" + wifiname + "\"";// \"转义字符,代表"//为成员变量赋值
            wifiCong.preSharedKey = "\"" + pwd + "\"";// WPA-PSK密码
            wifiCong.hiddenSSID = false;
            wifiCong.status = WifiConfiguration.Status.ENABLED;
            wifiId = wifimanager.addNetwork(wifiCong);// 将配置好的特定WIFI密码信息添加,添加完成后默认是不激活状态,成功返回ID,否则为-1
            if ( wifiId!=-1 ) {
                Log.e("MainActivity", "WiFi添加成功");
                //添加成功
            }else{
                Log.e("MainActivity", "WiFi添加失败");
                //添加失败
            }
            boolean isConected =  wifimanager.enableNetwork(wifiId, true);  // 连接配置好的指定ID的网络 true连接成功
            if ( isConected ) {
                Log.e("MainActivity", "WiFi连接成功");
                //连接成功
                WifiInfo info = wifimanager.getConnectionInfo();
            }else {
                Log.e("MainActivity", "WiFi连接失败");
                //连接失败
            }
        }

获取WiFi状态

注册广播

        mIntentFilter = new IntentFilter();
        mIntentFilter.addAction("android.net.wifi.STATE_CHANGE");//WiFi状态变化
        mIntentFilter.addAction("android.net.wifi.WIFI_STATE_CHANGED");//WiFi开关状态
        mWiFiChangeReceiver = new WiFiChangeReceiver();
        registerReceiver(mWiFiChangeReceiver,mIntentFilter);

接收广播处理

class WiFiChangeReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {

            if (intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
                int switchState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 0);//得到WiFi开关状态值
                switch (switchState) {
                    case WifiManager.WIFI_STATE_DISABLED://WiFi已关闭
                        WiFIStateData data1 = new WiFIStateData();
                        data1.time = mDf.format(System.currentTimeMillis());
                        data1.state = "WiFi关闭";
                        mDao.insert(data1);
                        EventBus.getDefault().post(msgData);
                        Log.e(TAG, "WiFi关闭");
                        break;
                    case WifiManager.WIFI_STATE_DISABLING://WiFi关闭中
                        Log.e(TAG, "WiFi关闭中");
                        break;
                    case WifiManager.WIFI_STATE_ENABLED://WiFi已开启
                        WiFIStateData data2 = new WiFIStateData();
                        data2.time = mDf.format(System.currentTimeMillis());
                        data2.state = "WiFi开启";
                        mDao.insert(data2);
                        EventBus.getDefault().post(msgData);
                        Log.e(TAG, "WiFi开启");
                        break;
                    case WifiManager.WIFI_STATE_ENABLING://WiFi开启中
                        Log.e(TAG, "WiFi开启中");
                        break;
                    case WifiManager.WIFI_STATE_UNKNOWN://WiFi状态未知
                        WiFIStateData data3 = new WiFIStateData();
                        data3.time = mDf.format(System.currentTimeMillis());
                        data3.state = "WiFi状态未知";
                        mDao.insert(data3);
                        EventBus.getDefault().post(msgData);
                        Log.e(TAG, "WiFi状态未知");
                        break;
                    default:
                        break;
                }
            }

                if (intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)){ //网络状态改变行为
                    Parcelable parcelableExtra = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);//得到信息包
                    if (parcelableExtra != null){
                        NetworkInfo networkInfo = (NetworkInfo)parcelableExtra;//得到网络信息
                        NetworkInfo.DetailedState detailedState = networkInfo.getDetailedState();
                        switch (detailedState){
                            case CONNECTED:
                                mDisconnectState = true;
                                WiFIStateData data4 = new WiFIStateData();
                                data4.time = mDf.format(System.currentTimeMillis());
                                data4.state = "已经连接";
                                mDao.insert(data4);
                                EventBus.getDefault().post(msgData);
                                Log.e(TAG, "已经连接");
                                break;
                            case DISCONNECTED:
                                if (mDisconnectState){
                                    mDisconnectState = false;
                                    WiFIStateData data5 = new WiFIStateData();
                                    data5.time = mDf.format(System.currentTimeMillis());
                                    data5.state = "已经断开";
                                    mDao.insert(data5);
                                    EventBus.getDefault().post(msgData);
                                    Log.e(TAG, "已经断开");
                                }
                                break;
                            case IDLE:

                                WiFIStateData data6 = new WiFIStateData();
                                data6.time = mDf.format(System.currentTimeMillis());
                                data6.state = "空闲中";
                                mDao.insert(data6);
                                EventBus.getDefault().post(msgData);
                                Log.e(TAG, "空闲中");

                                break;
                            case AUTHENTICATING:

                                WiFIStateData data7 = new WiFIStateData();
                                data7.time = mDf.format(System.currentTimeMillis());
                                data7.state = "认证中";
                                mDao.insert(data7);
                                EventBus.getDefault().post(msgData);
                                Log.e(TAG, "认证中");

                                break;
                            case BLOCKED:

                                WiFIStateData data8 = new WiFIStateData();
                                data8.time = mDf.format(System.currentTimeMillis());
                                data8.state = "认证失败";
                                mDao.insert(data8);
                                EventBus.getDefault().post(msgData);
                                Log.e(TAG, "认证失败");

                                break;
                            case CAPTIVE_PORTAL_CHECK:

                                WiFIStateData data9 = new WiFIStateData();
                                data9.time = mDf.format(System.currentTimeMillis());
                                data9.state = "连接检查";
                                mDao.insert(data9);
                                EventBus.getDefault().post(msgData);
                                Log.e(TAG, "连接检查");

                                break;
                            default:
                                break;
                        }
                    }

            }

        }
    }

WIFI热点

注意WiFi热点除了WiFi权限以外,如果要创建wifi热点还需要一个系统权限 android.permission.WRITE_SETTINGS。

但是这种系统权限在6.0版本后无法直接静态或者动态授权(十分无语)。所以在下面的代码中setPermissions方法就是添加设置权限的办法。


/*
content:创建WiFi热点class
time:2018-7-23 11:23
build:
 */

public class WiFiAP {
    private static WiFiAP mWiFiAP;
    private static WifiManager mWifManager;
    private WiFiAP(){}

    public static WiFiAP getI(){
        if (mWiFiAP == null){
            mWiFiAP = new WiFiAP();
        }
        return mWiFiAP;
    }

    /**
     * 手动得到系统权限的方法,提供给外部启动系统权限界面,以实现手动添加系统权限
     * @param context 外部activity的上下文
     */
    public void setPermissions(Context context){
        Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);
        intent.setData(Uri.parse("package:" + context.getPackageName()));
        context.startActivity(intent);

    }

    /**
     * 打开热点并且创建WiFi热点的方法
     * @param context 外部上下文
     * @param ssid 要创建WiFi热点的账号名称
     * @param password 要创建WiFi热点的密码
     * 注意,此方法直接使用WPA2_PSK 的安全策略创建WiFi热点,低版本的Android系统如果需要使用请切换。
     */
    @SuppressLint("MissingPermission")
    public void openWiFiAP(Context context, String ssid, String password){

        mWifManager = (WifiManager)context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);

        if (mWifManager.isWifiEnabled()) {
            //如果wifi处于打开状态,则关闭wifi,
            mWifManager.setWifiEnabled(false);
        }
        WifiConfiguration config = new WifiConfiguration();
        config.SSID = ssid;
        config.preSharedKey = password;
        config.hiddenSSID = false;//是否隐藏热点true=隐藏
        config.allowedAuthAlgorithms
                .set(WifiConfiguration.AuthAlgorithm.OPEN);//开放系统认证
        config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
        int indexOfWPA2_PSK = 4;
        //从WifiConfiguration.KeyMgmt数组中查找WPA2_PSK的值
        for (int i = 0; i < WifiConfiguration.KeyMgmt.strings.length; i++)
        {
            if(WifiConfiguration.KeyMgmt.strings[i].equals("WPA2_PSK"))
            {
                indexOfWPA2_PSK = i;
                break;
            }
        }
        //WifiConfiguration.KeyMgmt.WPA_PSK
        config.allowedKeyManagement.set(indexOfWPA2_PSK);
        config.allowedPairwiseCiphers
                .set(WifiConfiguration.PairwiseCipher.TKIP);
        config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
        config.allowedPairwiseCiphers
                .set(WifiConfiguration.PairwiseCipher.CCMP);
        config.status = WifiConfiguration.Status.ENABLED;
        //通过反射调用设置热点
        try {
            Method method = mWifManager.getClass().getMethod(
                    "setWifiApEnabled", WifiConfiguration.class, Boolean.TYPE);
            boolean enable = (Boolean) method.invoke(mWifManager, config, true);

            if (enable) {
                Log.e("WiFiAP", "热点已开启 SSID:" + ssid + " Password:"+password);
            } else {
                Log.e("WiFiAP", "创建热点失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("WiFiAP", "创建热点失败"+e);
        }

    }

    /**
     * 关闭WiFi热点的方法
     * @param context 外部activity的上下文
     */
    public void closeWiFiAP(Context context){
        mWifManager = (WifiManager)context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        if( mWifManager == null){
            Log.e("closeWiFiAP", "Error: mWifManager is null");
            return;
        }
        try {
            Method method = mWifManager.getClass().getMethod("getWifiApConfiguration");
            method.setAccessible(true);
            WifiConfiguration config = (WifiConfiguration) method.invoke(mWifManager);
            Method method2 = mWifManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
            method2.invoke(mWifManager, config, false);
            //mText.setText("wifi热点关闭");
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

    }
}

蓝牙

首先分享2个写的很好的蓝牙博客,非常全面,只是个别细节没有照顾到。

https://blog.csdn.net/a1533588867/article/details/52442349

https://blog.csdn.net/s13383754499/article/details/78436023

首先添加蓝牙权限一组:

     <!-- 蓝牙权限 -->
        <uses-permission android:name="android.permission.BLUETOOTH" />
        <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
        <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

废话不多说,直接上代码,都有注释:

1.打开蓝牙,关闭蓝牙。

public class BTDemo extends AppCompatActivity implements View.OnClickListener{
    private final String TAG = "BTDemo";
    private Button btn_bt_open,btn_bt_close,btn_bt_goSttings,btn_bt_visible,in_BTList;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_btdemo);
        btn_bt_open = (Button)findViewById(R.id.btn_BT_open);
        btn_bt_close = (Button)findViewById(R.id.btn_BT_close);
        btn_bt_visible = (Button)findViewById(R.id.btn_BT_visible);
        btn_bt_goSttings = (Button)findViewById(R.id.btn_BT_GoSttings);
        in_BTList = (Button)findViewById(R.id.in_BTList);
        btn_bt_open.setOnClickListener(this);
        btn_bt_close.setOnClickListener(this);
        btn_bt_visible.setOnClickListener(this);
        btn_bt_goSttings.setOnClickListener(this);
        in_BTList.setOnClickListener(this);
    }
    //打开蓝牙
    public void openBT(){
        //创建蓝牙适配器
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (bluetoothAdapter == null){
            Log.e(TAG, "该设备不支持蓝牙");
        }
        if(!bluetoothAdapter.isEnabled()){
            Log.e(TAG, "准备打开蓝牙" );
            //弹窗询问方式打开蓝牙
            Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);//蓝牙适配器. 行动-请求-打开
            //startActivity(intent);也可以使用这个
            startActivityForResult(intent,RESULT_OK);
            //bluetoothAdapter.enable(); 不询问直接打开蓝牙
        }
    }
    //关闭蓝牙
    public void  closeBT(){
        Log.e(TAG, "coloseBT 被调用" );
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if(bluetoothAdapter.isEnabled()){
            bluetoothAdapter.disable();
        }
    }
    //跳转到设置-蓝牙界面中
    public void settingsOpen(){
        Intent intent = new Intent(Settings.ACTION_BLUETOOTH_SETTINGS);
        startActivity(intent);
    }
    //蓝牙可见(蓝牙可以被其他设备发现)
    public void btVisible(){
        BluetoothAdapter blueteoothAdapter = BluetoothAdapter.getDefaultAdapter();
        //开启被其它蓝牙设备发现的功能
        //getScanMode 获得扫描模式                                    扫描-模式-连接-发现
        if (blueteoothAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
            Intent i = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);//行动-请求-发现
            //设置为一直开启 0是一直开着,如果设置了时间就会按照设置时间显示蓝牙可见
            i.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 0);
            startActivity(i);
        }
    }
 
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_BT_open:
                openBT();
                break;
            case R.id.btn_BT_close:
                closeBT();
                break;
            case R.id.btn_BT_visible:
                btVisible();
                break;
            case R.id.btn_BT_GoSttings:
                settingsOpen();
                break;
            case R.id.in_BTList:
                Intent intent = new Intent(BTDemo.this,BTListView.class);
                startActivity(intent);
                break;
            default:
                break;
        }
 
    }
}

2.蓝牙搜索与蓝牙内容列表显示:

public class BTListView extends AppCompatActivity {
    private ListView listView;
    private ArrayAdapter mArrayAdapter;
    private BluetoothAdapter mBluetoothAdapter;
    private BroadcastReceiver broadcastReceiver;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_btlist_view);
        //创建蓝牙适配器
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        //搜索蓝牙
        mBluetoothAdapter.startDiscovery();
 
        listView = (ListView) findViewById(R.id.BTlistView);
        //创建listView的适配器
        mArrayAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1);
        //意图过滤器
        IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        //创建广播接收器
        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                //获得intent的行动
                String action = intent.getAction();
                /*
                三组蓝牙广播状态分别是:
                BluetoothAdapter.ACTION_DISCOVERY_STARTED  开始蓝牙搜索
                BluetoothDevice.ACTION_FOUND  蓝牙搜索中
                BluetoothAdapter.ACTION_DISCOVERY_FINISHED 蓝牙搜索完毕
                 */
                if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                    //创建蓝牙设备,我们可以从BluetoothDevice 里获得各种信息 名称、地址 等等
                    BluetoothDevice bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                    // 将设备名称和地址放入array adapter,以便在ListView中显示
                    mArrayAdapter.add(bluetoothDevice.getName() + "\n" + bluetoothDevice.getAddress());
                } else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
                    Toast.makeText(BTListView.this,"开始搜索", Toast.LENGTH_SHORT).show();
                } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                    Toast.makeText(BTListView.this,"搜索完毕",Toast.LENGTH_SHORT).show();
                }
            }
        };
        //添加广播寄存器
        registerReceiver(broadcastReceiver,intentFilter);
        listView.setAdapter(mArrayAdapter);
    }
 
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mBluetoothAdapter.cancelDiscovery();// 取消搜索蓝牙
        unregisterReceiver(broadcastReceiver);//注销广播接收器
 
    }
}

 

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值