BluetoothUtil

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothClass;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;

public class BluetoothUtil {

/**
 * 藍牙是否打開
 */
public static boolean isBluetoothOn() {
	BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
	if (mBluetoothAdapter != null)
		// 藍牙已打開
		if (mBluetoothAdapter.isEnabled())
			return true;

	return false;
}

/**
 * 獲取所有已配對的設備
 */
public static List<BluetoothDevice> getPairedDevices() {
	List deviceList = new ArrayList<>();
	Set<BluetoothDevice> pairedDevices = BluetoothAdapter.getDefaultAdapter().getBondedDevices();
	if (pairedDevices.size() > 0) {
		for (BluetoothDevice device : pairedDevices) {
			deviceList.add(device);
		}
	}
	return deviceList;
}

/**
 * 獲取所有已配對的打印類設備
 */
public static List<BluetoothDevice> getPairedPrinterDevices() {
	return getSpecificDevice(BluetoothClass.Device.Major.IMAGING);
}

/**
 * 從已配對設配中,刪選出某一特定類型的設備展示
 * @param deviceClass
 * @return
 */
public static List<BluetoothDevice> getSpecificDevice(int deviceClass){
	List<BluetoothDevice> devices = BluetoothUtil.getPairedDevices();
	List<BluetoothDevice> printerDevices = new ArrayList<>();

	for (BluetoothDevice device : devices) {
		BluetoothClass klass = device.getBluetoothClass();
		// 關於藍牙設備分類參考 http://stackoverflow.com/q/23273355/4242112
		if (klass.getMajorDeviceClass() == deviceClass)
			printerDevices.add(device);
	}

	return printerDevices;
}

/**
 * 彈出系統對話框,請求打開藍牙
 */
public static void openBluetooth(Activity activity) {
	Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
	activity.startActivityForResult(enableBtIntent, 666);
}

public static BluetoothSocket connectDevice(BluetoothDevice device) {
	BluetoothSocket socket = null;
	try {
		socket = device.createRfcommSocketToServiceRecord(
				UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
		socket.connect();
	} catch (IOException e) {
		try {
			socket.close();
		} catch (IOException closeException) {
			return null;
		}
		return null;
	}
	return socket;
}

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章