1. 程式人生 > >android -------- 藍牙Bluetooth

android -------- 藍牙Bluetooth

靜態方法 class 藍牙設備 level 專業 style 調用 直接 show

什麽是藍牙?

也可以說是藍牙技術。所謂藍牙(Bluetooth)技術,實際上是一種短距離無線電技術,是由愛立信公司公司發明的。利用“藍牙”技術,能夠有效地簡化掌上電腦、筆記本電腦和移動電話手機等移動通信終端設備之間的通信,也能夠成功地簡化以上這些設備與因特網Internet之間的通信,從而使這些現代通信設備與因特網之間的數據傳輸變得更加迅速高效,為無線通信拓寬道路。

Android 4.3(API Level 18)開始引入Bluetooth Low Energy(BLE,低功耗藍牙)的核心功能並提供了相應的 API, 應用程序通過這些 API 掃描藍牙設備、查詢 services、讀寫設備的 characteristics(屬性特征)等操作。

Android BLE 使用的藍牙協議是 GATT 協議,有關該協議的詳細內容可以參見藍牙官方文檔。以下我引用一張官網的圖來大概說明 Android 開發中我們需要了解的一些 Bluetooth Low Energy 的專業術語。

Android提供BluetoothAdapter類藍牙通信。通過調用創建的對象的靜態方法getDefaultAdapter()。其語法如下給出。

   mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

首先需要AndroidManifest.xml文件中添加操作藍牙的權限。

<!--
需要此權限來執行任何藍牙通信,如請求一個連接、接受一個連接和傳輸數據。--> <uses-permission android:name="android.permission.BLUETOOTH"/> <!-- //如果你想讓你的應用啟動設備發現或操縱藍牙設置,必須申報bluetooth_admin許可--> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

驗證藍牙是否開啟,未開啟的提示開啟

if (!mBluetoothAdapter.isEnabled()){
      
//彈出對話框提示用戶是後打開 Intent enabler = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enabler, REQUEST_ENABLE); }

Activity代碼:

/**
 * Created by zhangqie on 2017/11/28.
 */

public class BluetoothActivity extends AppCompatActivity implements View.OnClickListener{


    private static final int REQUEST_ENABLE = 1;

    private static final String TAG = Demo1Activity.class.getName();


    BluetoothAdapter mBluetoothAdapter;

    TextView tvDevices;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.demo1);
        initView();
    }

    private void initView(){

        findViewById(R.id.btn1).setOnClickListener(this);
        tvDevices = (TextView) findViewById(R.id.textblue);

        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        if (!mBluetoothAdapter.isEnabled()){
            //彈出對話框提示用戶是後打開
            Intent enabler = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enabler, REQUEST_ENABLE);
            //不做提示,直接打開,不建議用下面的方法,有的手機會有問題。
            // mBluetoothAdapter.enable();
         }

        showBluetooth();

    }

    private void startSearthBltDevice() {
        //如果當前在搜索,就先取消搜索
        if (mBluetoothAdapter.isDiscovering()) {
            mBluetoothAdapter.cancelDiscovery();
        }
        //開啟搜索
        mBluetoothAdapter.startDiscovery();
    }


    private void showBoradCast(){
        // 設置廣播信息過濾
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothDevice.ACTION_FOUND);//每搜索到一個設備就會發送一個該廣播
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);//當全部搜索完後發送該廣播
        filter.setPriority(Integer.MAX_VALUE);//設置優先級
        // 註冊藍牙搜索廣播接收者,接收並處理搜索結果
        this.registerReceiver(receiver, filter);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn1:
                showBoradCast();
                startSearthBltDevice();
                break;
        }
    }

    //獲取已經配對的藍牙設備
    private void showBluetooth(){
        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
        if (pairedDevices.size() > 0) {
            for (BluetoothDevice device : pairedDevices) {
                tvDevices.append(device.getName() + ":" + device.getAddress());
            }
        }
    }


    /**
     * 定義廣播接收器
     */
    private final BroadcastReceiver receiver = 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);
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                    Log.i(TAG, ":"+ device.getAddress());
                    tvDevices.append(device.getName() + ":"+ device.getAddress());
                }
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {

                Toast.makeText(Demo1Activity.this,"已搜索完成",Toast.LENGTH_LONG).show();

                //已搜素完成
            }
        }
    };

}

得到效果圖:

技術分享圖片

android -------- 藍牙Bluetooth