BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (bluetoothAdapter == null) { // 设备不支持蓝牙 } else if (!bluetoothAdapter.isEnabled()) { // 蓝牙未开启 }
Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices(); boolean isConnected = false; for (BluetoothDevice device : pairedDevices) { if (device.getBondState() == BluetoothDevice.BOND_BONDED) { isConnected = true; break; } }
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED); registerReceiver(new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { int bondState = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR); // 处理状态变化 } }, filter);
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = cm.getActiveNetworkInfo(); boolean isConnected = networkInfo != null && networkInfo.isConnected();
网络类型 | 判断条件 |
---|---|
移动数据 | networkInfo.getType() == ConnectivityManager.TYPE_MOBILE |
WiFi | networkInfo.getType() == ConnectivityManager.TYPE_WIFI |
NetworkCapabilities capabilities = cm.getNetworkCapabilities(cm.getActiveNetwork()); boolean isInternet = capabilities != null && (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) || capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI));
WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE); boolean isWifiEnabled = wifiManager.isWifiEnabled();
WifiInfo wifiInfo = wifiManager.getConnectionInfo(); String currentSSID = wifiInfo.getSSID(); // 格式如 ""Your_SSID"" boolean isConnectedToTarget = currentSSID.equals(""Your_SSID"");
IntentFilter filter = new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION); registerReceiver(new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_UNKNOWN); // 处理状态变化 } }, filter);
功能 | 所需权限 |
---|---|
检测蓝牙状态 | BLUETOOTH |
检测网络状态 | ACCESS_NETWORK_STATE |
检测WiFi状态 | ACCESS_WIFI_STATE |
修改网络/WiFi状态 | CHANGE_NETWORK_STATE , CHANGE_WIFI_STATE |
解答:
注册 BluetoothDevice.ACTION_BOND_STATE_CHANGED
广播,监听 EXTRA_BOND_STATE
字段:
int bondState = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR); if (bondState == BluetoothDevice.BOND_NONE) { // 设备已断开连接 }
解答:
通过 ConnectivityManager
获取网络类型:
NetworkInfo networkInfo = cm.getActiveNetworkInfo(); boolean isMobile = networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_MOBILE;