今天面试问我做过蓝牙灯泡没,现在正好看一下,最近智能家居很火

蓝牙就好像一个美女,我要在这个情人节的夜晚,把它衣服一件一件脱光光,嘿嘿

这个代码适配的是4.0,之后的我就不知道是否可行了,我在这只是了解下

1. 原理图

Android 蓝牙如何使用_ide

2. 蓝牙 API

.getDefaultAdapter();
打开手机蓝牙
mBluetoothAdapter .enable();
关闭手机蓝牙
mBluetoothAdapter.disable();
扫描蓝牙设备
mBluetoothAdapter.startDiscovery();
取消扫描蓝牙设备,减少资源的消耗
mBluetoothAdapter.cancelDiscovery();

3. 添加蓝牙广播接受者

IntentFilter filter = new IntentFilter();
// 开始扫描的广播
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
// 扫描完成的广播
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
// 发现一个可用的设备的广播
filter.addAction(BluetoothDevice.ACTION_FOUND);
mBluetoothReceiver = new BluetoothReceiver();
//注册监听
registerReceiver(mBluetoothReceiver, filter);

4. 蓝牙广播接受者

class BluetoothReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
//根绝不同的action做判断,eg:获取蓝牙设备
}
}

5. 连接设备

public void connectServer(final BluetoothDevice device) {
new Thread(new Runnable(){
@Override
public void run() {
try {
System.out.println(randomUUID.toString());
BluetoothSocket clientSocket = device.
createRfcommSocketToServiceRecord(
UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"));
clientSocket.connect();
out = clientSocket.getOutputStream();
System.out.println("连接成功");
Looper.prepare();
Toast.makeText(BluetoothDemoActivity.this, "连接成功", 0).show();
Looper.loop();
} catch

6. 注销设备

注销广播接受者
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mBluetoothReceiver);
}

7. 代码

7.1 Activity

ublic class BlueToothActiity extends AppCompatActivity implements AdapterView.OnItemClickListener {

private ListView mLv;
private BluetoothAdapter mBluetoothAdapter;
private OutputStream mOutputStream;
private ArrayList<BluetoothDevice> mDevices = new ArrayList<BluetoothDevice>();
private BroadcastReceiver mBluetoothReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// 扫描到蓝牙设备
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
mDevices.add(device);
mAdapter.notifyDataSetChanged();
System.out.println("device name" + device.getName());
} else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
Toast.makeText(getApplicationContext(), "开始扫描", Toast.LENGTH_SHORT).show();
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
Toast.makeText(getApplicationContext(), "扫描结束", Toast.LENGTH_SHORT).show();
}
}
};
private DeviceAdapter mAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mLv = (ListView) findViewById(R.id.lv);
mAdapter = new DeviceAdapter(getApplicationContext(), mDevices);
mLv.setAdapter(mAdapter);
mLv.setOnItemClickListener(this);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// 注册广播接收者, 当扫描到蓝牙设备的时候, 系统会发送广播
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mBluetoothReceiver, filter);
}

public void clickBtn(View v) {
switch (v.getId()) {
case R.id.button1:
// 蓝牙是否可用
if (!mBluetoothAdapter.isEnabled()) {
// 打开蓝牙
mBluetoothAdapter.enable();
}
break;
case R.id.button2:
// 关闭蓝牙
if (mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.disable();
}
break;
case R.id.button3:
// 开始扫描
mDevices.clear();
mAdapter.notifyDataSetChanged();
mBluetoothAdapter.startDiscovery();
break;
case R.id.button4:
// 停止扫描
mBluetoothAdapter.cancelDiscovery();
break;
case R.id.button5:
sendCtrl(0);
break;
case R.id.button6:
sendCtrl(1);
break;
case R.id.button7:
sendCtrl(2);
break;
default:
break;
}
}

private void sendCtrl(int i) {
try {
byte[] bs = new byte[5];
bs[0] = (byte)0x01;
bs[1] = (byte)0x99;
if(i== 0) {
bs[2] = (byte)0x10;
bs[3] = (byte)0x10;
}else if(i==1) {
bs[2] = (byte)0x11;
bs[3] = (byte)0x11;
}else if(i==2) {
bs[2] = (byte)0x17;
bs[3] = (byte)0x17;
}
bs[4] = (byte)0x99;
mOutputStream.write(bs);
} catch (IOException e) {
e.printStackTrace();
}
}

@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mBluetoothReceiver);
}

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
BluetoothDevice device = mDevices.get(position);
conn(device);
}

private void conn(final BluetoothDevice device) {
// 建立蓝牙连接是耗时操作, 类似TCP Socket, 需要放在子线程里
new Thread() {
public void run() {
try {
// 获取 BluetoothSocket, UUID需要和蓝牙服务端保持一致
BluetoothSocket bluetoothSocket = device.createRfcommSocketToServiceRecord(UUID
.fromString("00001101-0000-1000-8000-00805F9B34FB"));
// 和蓝牙服务端建立连接
bluetoothSocket.connect();
// 获取输出流, 往蓝牙服务端写指令信息
mOutputStream = bluetoothSocket.getOutputStream();
// 提示用户
runOnUiThread(new Runnable() {
public void run() {
System.out.println("连接成功----");
Toast.makeText(getApplicationContext(), "连接成功", Toast.LENGTH_SHORT)
.show();
}
});
} catch

7.2 Adapter

public class DeviceAdapter extends BaseAdapter



private ArrayList<BluetoothDevice> mDevices;
private Context mContext;

public DeviceAdapter(Context context, ArrayList<BluetoothDevice> devices) {
mDevices = devices;
mContext = context;
}

@Override
public int getCount() {
return mDevices.size();
}

@Override
public Object getItem(int position) {
return null;
}

@Override
public long getItemId(int position) {
return 0;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null) {
convertView = View.inflate(mContext, R.layout.bluetooth_item, null);
holder = new ViewHolder();
holder.mTvName = (TextView) convertView.findViewById(R.id.tv_name);
holder.mTvAddress = (TextView) convertView.findViewById(R.id.tv_address);
convertView.setTag(holder);
}else {
holder = (ViewHolder) convertView.getTag();
}
BluetoothDevice device = mDevices.get(position);
holder.mTvName.setText(device.getName());
holder.mTvAddress.setText(device.getAddress());
return

7.3 布局

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:onClick="clickBtn"
android:text="打开蓝牙"

<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="@+id/button1"
android:onClick="clickBtn"
android:text="关闭蓝牙"

<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/button1"
android:onClick="clickBtn"
android:text="开始扫描"

<Button
android:id="@+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/button3"
android:layout_alignBottom="@+id/button3"
android:layout_alignLeft="@+id/button2"
android:onClick="clickBtn"
android:text="停止扫描"

<Button
android:id="@+id/button5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/button3"
android:onClick="clickBtn"
android:text="开灯"

<Button
android:id="@+id/button7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/button6"
android:layout_alignBottom="@+id/button6"
android:layout_toRightOf="@+id/button6"
android:onClick="clickBtn"
android:text="点动"

<ListView
android:id="@+id/lv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/button7"
</ListView>

<Button
android:id="@+id/button6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/button5"
android:layout_alignBottom="@+id/button5"
android:layout_toRightOf="@+id/button5"
android:onClick="clickBtn"
android:text="关灯"

</RelativeLayout>