這不是廣告
首先得需要一個藍牙控制器 然後再操作
我在某寶發現了這樣的 附位址
https://item.taobao.com/item.htm?spm=a230r.1.14.45.YzSGuI&id=42767906785&ns=1&abbucket=1#detail
butterknife的使用在我别的部落格上有
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsICdzFWRoRXdvN1LclHdpZXYyd2LcBzNvwVZ2x2bzNXak9CX90TQNNkRrFlQKBTSvwFbslmZvwFMwQzLcVmepNHdu9mZvwFVywUNMZTY18CX052bm9CX9cmaONTTE9EeRpWTyEEWiZXUYpVd1kmYr50MZV3YyI2cKJDT29GRjBjUIF2LcRHelR3LcJzLctmch1mclRXY39TN1IjN1QDN1EzMxEDM3EDMy8CX0Vmbu4GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.jpg)
這個是布局圖 因為要在真機測試 很麻煩
不過我這是完美運作後的代碼
多說無益 代碼才是最好的老師
MainActivity
package com.example.lanya;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.UUID;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class MainActivity extends AppCompatActivity {
@Bind(R.id.bt_open)
Button btOpen;
@Bind(R.id.bt_close)
Button btClose;
@Bind(R.id.bt_scannle)
Button btScannle;
@Bind(R.id.bt_closescannle)
Button btClosescannle;
@Bind(R.id.bt_open_light)
Button btOpenLight;
@Bind(R.id.bt_close_light)
Button btCloseLight;
@Bind(R.id.bt_close_time)
Button btCloseTime;
@Bind(R.id.lv_result)
ListView lvResult;
@Bind(R.id.activity_main)
LinearLayout activityMain;
private BluetoothAdapter mBluetoothAdapter;
private MyReceiver mReceiver;
private IntentFilter mFilter;
private ArrayList<BluetoothDevice> mList = new ArrayList<>();
private MyAdapter myAdapter;
private OutputStream outputStream;
private int OPEN=0x10;
private int CLOASE=0x11;
private int OPEN4S=0x19;
private BluetoothSocket bluetoothSocket;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
//藍牙入口類對象 如果沒有則傳回空
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
//注冊接受藍牙裝置的廣播
mReceiver = new MyReceiver();
mFilter = new IntentFilter();
mFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
mFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
mFilter.addAction(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, mFilter);
lvResult.setOnItemClickListener(new MyOnItemClick());
}
@OnClick({R.id.bt_open, R.id.bt_close, R.id.bt_scannle, R.id.bt_closescannle, R.id.bt_open_light, R.id.bt_close_light, R.id.bt_close_time})
public void onClick(View view) {
if (mBluetoothAdapter == null) {
Toast.makeText(this, "藍牙不可用", Toast.LENGTH_SHORT).show();
return;
}
switch (view.getId()) {
case R.id.bt_open:
//打開藍牙
mBluetoothAdapter.enable();
break;
case R.id.bt_close:
mBluetoothAdapter.disable();
break;
case R.id.bt_scannle:
if(mList.size()>0){
mList.clear();
}
if (mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.startDiscovery();
}
break;
case R.id.bt_closescannle:
if (mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.cancelDiscovery();
}
break;
case R.id.bt_open_light:
sendCMD(OPEN);
break;
case R.id.bt_close_light:
sendCMD(CLOASE);
break;
case R.id.bt_close_time:
sendCMD(OPEN4S);
break;
}
}
class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
switch (intent.getAction()) {
//掃描開始
case BluetoothAdapter.ACTION_DISCOVERY_STARTED:
Toast.makeText(context, "掃描開始", Toast.LENGTH_SHORT).show();
break;
//掃描結束
case BluetoothAdapter.ACTION_DISCOVERY_FINISHED:
Toast.makeText(context, "掃描結束", Toast.LENGTH_SHORT).show();
break;
//找到裝置
case BluetoothDevice.ACTION_FOUND:
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// Toast.makeText(context, "找到裝置" + device.getName(), Toast.LENGTH_SHORT).show();
mList.add(device);
if(myAdapter==null) {
myAdapter = new MyAdapter();
}
lvResult.setAdapter(myAdapter);
break;
}
}
}
class MyAdapter extends BaseAdapter {
@Override
public int getCount() {
return mList.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) {
if (convertView == null) {
convertView = View.inflate(getApplicationContext(), R.layout.listview_item, null);
}
TextView name = (TextView)convertView.findViewById(R.id.tv_name);
TextView adress = (TextView)convertView.findViewById(R.id.tv_adress);
name.setText(mList.get(position).getName());
adress.setText(mList.get(position).getAddress());
return convertView;
}
}
class MyOnItemClick implements AdapterView.OnItemClickListener{
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
BluetoothDevice device = mList.get(position);
connect(device);
}
}
private void sendCMD(int cmd){
if(outputStream!=null){
try {
byte[] bytes = new byte[5];
bytes[0]=(byte)0x01;
bytes[1]=(byte)0x99;
bytes[2]=(byte)cmd;
bytes[3]=(byte)cmd;
bytes[4]=(byte)0x99;
outputStream.write(bytes);
outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void connect(final BluetoothDevice device) {
new Thread(){
@Override
public void run() {
try {
bluetoothSocket = device.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"));
bluetoothSocket.connect();;//耗時操作
//擷取輸出流
MainActivity.this.outputStream = outputStream;
outputStream = bluetoothSocket.getOutputStream();
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "連接配接成功", Toast.LENGTH_SHORT).show();
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
@Override
protected void onDestroy() {
super.onDestroy();
if(outputStream!=null){
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
outputStream=null;
}
if(bluetoothSocket!=null&&bluetoothSocket.isConnected()){
try {
bluetoothSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
bluetoothSocket=null;
}
unregisterReceiver(mReceiver);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.lanya.MainActivity">
<LinearLayout
android:layout_margin="7dp"
android:layout_width="match_parent"
android:orientation="horizontal"
android:layout_height="wrap_content">
<Button
android:id="@+id/bt_open"
android:text="打開藍牙"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content" />
<Button
android:id="@+id/bt_close"
android:text="打開藍牙"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:layout_margin="7dp"
android:layout_width="match_parent"
android:orientation="horizontal"
android:layout_height="wrap_content">
<Button
android:id="@+id/bt_scannle"
android:text="掃描裝置"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content" />
<Button
android:id="@+id/bt_closescannle"
android:text="關閉掃描"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:layout_margin="7dp"
android:layout_width="match_parent"
android:orientation="horizontal"
android:layout_height="wrap_content">
<Button
android:id="@+id/bt_open_light"
android:text="開燈"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content" />
<Button
android:id="@+id/bt_close_light"
android:text="關燈"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content" />
<Button
android:id="@+id/bt_close_time"
android:text="定時關閉(點動)"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content" />
</LinearLayout>
<ListView
android:id="@+id/lv_result"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
listview_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="@+id/tv_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:textColor="#F00"
android:textSize="15sp" />
<TextView
android:id="@+id/tv_adress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#F00"
android:textSize="15sp" />
</LinearLayout>
額 少了倆權限 尴尬
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>