藍牙打開和關閉

實例化藍牙對象

BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
  • 示例

public class BluetoothManager  {

    private static  BluetoothManager manager ;
    private BluetoothAdapter bluetoothAdapter;

    private BluetoothManager(){
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    }

    public BluetoothAdapter getBluetoothAdapter() {
        return bluetoothAdapter;
    }

    public static BluetoothManager newInstance(){
        if (null == manager){
            synchronized (BluetoothManager.class){
                if (null==manager){
                    manager = new BluetoothManager();
                }
            }
        }
        return manager ;
    }



    /**
     * 是否支持藍牙
     *
     * @return
     */
    public boolean isSupportBluetooth(){
        return bluetoothAdapter!=null;
    }

    /**
     * 藍牙是否打開   true爲打開
     * @return
     */
    public boolean isBlueEnable() {
        return isSupportBluetooth() && bluetoothAdapter.isEnabled();
    }


是否支持藍牙

 /**
     * 是否支持藍牙
     *
     * @return
     */
    public boolean isSupportBluetooth(){
        return bluetoothAdapter!=null;
    }

藍牙是否打開 true爲打開

public boolean isBlueEnable() {
        return isSupportBluetooth() && bluetoothAdapter.isEnabled();
    }

打開藍牙

  • 方式一
  public void openBluetooth(){
        if (!BluetoothManager.newInstance().isBlueEnable()){
            BluetoothManager.newInstance().getBluetoothAdapter().enable();
        }
    }
  • 方式二
 public void openBluetooth1(){
        if (!BluetoothManager.newInstance().isBlueEnable()){
            Intent intent=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            activity.startActivityForResult(intent, 100);
        }
    }

關閉藍牙

public void closeBluetooth(){
        if (BluetoothManager.newInstance().isBlueEnable()){
            BluetoothManager.newInstance().getBluetoothAdapter().disable();
        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章