Android BLE 藍牙編程(一)


最近在研究這個,等我有時間來寫吧!

終於在端午節給自己放個假,現在就來說說關於android藍牙ble的

最近的學習成果吧!!

需要材料(寫個簡單教程吧~~關於小米手環的哦!嘿嘿)

 

Android 手機一部 要求android 4.3 系統以上

小米手環一個 一代最好 (我手里只有一代的 , 二代有沒有修改uuid 我不清楚)

 

首先說明想要使用android做藍牙ble的開發首先需要Android 4.3以上的系統哦!這個應該不難,目前大部分Android手機都比這個版本高吧

下面就讓我們開始吧~

 

首先先了解下基礎知識!看看系統先幫我們做好了那些事情吧!~

上圖!!

這些是Android 系統為我們做的事 

首先看BluetoothAdapter

這是系統提供的藍牙適配器。在使用手機的藍牙功能前一定是要先獲取的。

該適配器提供了一個掃描方法( bluetoothAdapter.startLeScan(callback) ),可以用它來獲取藍牙設備。是不是很貼心啊~~

掃描完設備之后 回調方法中會得到掃描到的設備信息放在bluetoothdevice中

選擇我們需要的設備后可以通過 bluetoothdevice的connectGatt方法連接設備。

哎呀~說的太復雜。還是在項目里說明吧!

先布局:

就簡單的做成這樣的。

小米手環有震動 和計步的功能,我們就在下面展示下計步和電池電量。

主要玩它的震動功能~嘿嘿~~~

簡單的寫個線性布局。

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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.wbnq.shouhuan.MainActivity">

    <Button
        android:id="@+id/saomiao"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="掃描設備"/>
    <Button
        android:id="@+id/zhendong"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="短震 / 嘿嘿嘿"/>
    <Button
        android:id="@+id/changzhen"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="長震 / 呵呵呵"/>
    <Button
        android:id="@+id/buting"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="不要停 / 哈哈哈"/>
    <Button
        android:id="@+id/tingxia"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="停下來 / ~~"/>

    <TextView
        android:id="@+id/jibu"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="走了多少步:"
        android:gravity="center"
        android:textSize="20dp"/>


    <TextView
        android:id="@+id/dianliang"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="電池電量"
        android:gravity="center"
        android:textSize="20dp"/>

    <TextView
        android:id="@+id/lianjiezhuangtai"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="連接狀態:未連接"
        android:gravity="center"
        android:textSize="20dp"/>



</LinearLayout>
View Code

正戲來啦:

MainActivity.java:

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private Button saomiao , duanzhen , changzhen , buting , tingxia;
    private TextView jibu , dianliang , lianjiezhuangtai;
    
    BluetoothAdapter bluetoothAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();

        //藍牙管理,這是系統服務可以通過getSystemService(BLUETOOTH_SERVICE)的方法獲取實例
        BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
        //通過藍牙管理實例獲取適配器,然后通過掃描方法(scan)獲取設備(device)
        bluetoothAdapter = bluetoothManager.getAdapter();
        
        
    }

    private void initView() {
        saomiao = (Button) findViewById(R.id.saomiao);
        duanzhen = (Button) findViewById(R.id.zhendong);
        changzhen = (Button) findViewById(R.id.changzhen);
        buting = (Button) findViewById(R.id.buting);
        tingxia = (Button) findViewById(R.id.tingxia);

        jibu = (TextView) findViewById(R.id.jibu);
        dianliang = (TextView) findViewById(R.id.dianliang);
        lianjiezhuangtai = (TextView) findViewById(R.id.lianjiezhuangtai);



    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.saomiao:

                break;
            case R.id.zhendong:

                break;
            case R.id.changzhen:

                break;
            case R.id.buting:

                break;
            case R.id.tingxia:

                break;

        }
    }
}
View Code

這個是基本框架。

我們看到在onCreate方法中 我們獲取了

BluetoothManager實例,並通過該實例獲取了系統的藍牙適配器
bluetoothAdapter
        //藍牙管理,這是系統服務可以通過getSystemService(BLUETOOTH_SERVICE)的方法獲取實例
        BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
        //通過藍牙管理實例獲取適配器,然后通過掃描方法(scan)獲取設備(device)
        bluetoothAdapter = bluetoothManager.getAdapter();

另外,想要正常執行的話還需要添加必須的權限:(目前需要的,后面還會加入新權限)

<uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

下面我們來實現掃描方法吧!

首先,想要實現掃描功能自然要先打開藍牙啦!!

請求開啟藍牙的代碼:

//開始掃描前開啟藍牙
Intent turn_on = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turn_on, 0);
Toast.makeText(MainActivity.this, "藍牙已經開啟", Toast.LENGTH_SHORT).show();

因為掃描是個耗時操作,所以最好把它寫在線程當中:

Thread scanThread = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Log.i("TAG", "run: saomiao ...");
                        saomiao();
                    }
                });

掃描方法:

public void saomiao(){
        deviceList.clear();
        bluetoothAdapter.startLeScan(callback);
    }

代碼很簡單是吧!的確~

deviceList是個bluetoothdevice的數組(List<BluetoothDevice> deviceList = new ArrayList<>();)

用來存放掃描來的所有device。用之前當然要先清理(clear)一下啦~

然后使用 bluetoothAdapter提供的掃描方法掃描藍牙ble設備(這里當然就是小米手環啦)

掃描方法有個回調:

//掃描回調
public BluetoothAdapter.LeScanCallback callback = new BluetoothAdapter.LeScanCallback() {
    @Override
    public void onLeScan(final BluetoothDevice bluetoothDevice, int i, byte[] bytes) {
        Log.i("TAG", "onLeScan: " + bluetoothDevice.getName() + "/t" + bluetoothDevice.getAddress() + "/t" + bluetoothDevice.getBondState());

        //重復過濾方法,列表中包含不該設備才加入列表中,並刷新列表
        if (!deviceList.contains(bluetoothDevice)) {
            //將設備加入列表數據中
            deviceList.add(bluetoothDevice);
        }

    }
};

將前面掃描到的數據放進deviceList列表中。

這里如果直接運行的話肯定會彈出個要獲取位置的錯誤。不多說

為項目添加位置權限:

    <!-- Android6.0 藍牙掃描才需要-->
    <uses-permission-sdk-23 android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

為啥要位置權限我也不清楚。還需要研究呢。

現在已經可以掃描咯!

看看都掃描到那些設備把:

千萬別以為我有那么多藍牙設備哦!其實仔細看原來只有兩個~~

沒錯~一個是手環另一個是其他藍牙ble設備,為啥會出來這么多呢?

因為每個開着的藍牙ble設備一直都在以固定的頻率發出服務(例如1s/1次)以便手機搜索到該設備

所以這個掃描我們才要寫進線程里啊~~

那如何停止掃描呢?很簡單哦!

開啟掃描的方法記得么?

 bluetoothAdapter.startLeScan(callback);

關閉的方法基本一樣,系統也提供了對應的停止方法:

 bluetoothAdapter.stopLeScan(callback);

很方便吧?

下一節我們讓設備在手機上以列表形式顯示出來吧~~

大家加油啦~~~

 

 

android 系統調用shell腳本

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM