Android手機通過藍牙向目標設備(ble)傳輸消息

最近一直在研究兩個手機用過藍牙通信,參考了部分網上代碼,到最後也沒弄清楚。(樓主是學渣......)

然後有一個項目要用手機通過藍牙控制三色燈,我就隨意寫了一下客戶端的應用程序,而且沒有測試,通過博客記錄一下方便以後使用測試。閒話不多說。開始----

參考部分網上代碼:

附上鍊接:http://blog.csdn.net/liuyu973971883/article/details/52495054

該代碼可以使用(親測),我是得到的APK獲取到了我手機原先配對過的藍牙設備的地址,通過日誌打印出來,作爲我項目的一個目標設備。大家也可以試一試,其中的邏輯講的非常清楚。

我講講我自己的小測試。

佈局文件:

由開啓藍牙,關閉藍牙,紅燈,綠燈,藍燈,關燈按鈕構成。

主活動:

UUID 統一標識碼 

最主要的還是關於BluetoothSocket和BluetoothServerSocket,大家可以看一下API文檔。

一,非涉及藍牙部分,純粹的亂寫代碼

主要思路是:按紅燈,紅燈按鈕背景顏色變紅,其他變灰色,其他一樣。

二,藍牙部分,該部分思路也是比較亂

首先我已經獲取到目標藍牙設備的地址,所以我只要連接發送就行,並且只要客戶端顯示成功發送,那就說明客戶端是正確的。只是我發了,服務器端收不到,因爲根本沒有服務器端接受。

1.添加權限

2.代碼中需要檢測安裝APK的機器是支持藍牙,若不支持,那...

3.獲取本地藍牙適配器

4.選中發送數據的藍牙設備

5.獲取到客戶端接口

6.向服務器端發送連接

7.獲取字符輸出流

8.發送數據

9.完成

大家可以根據我的代碼自己測試一下,然後下一個服務端接收。(我也很是需要)。
<?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:orientation="vertical">

    <Button
        android:id="@+id/open_bluetooth"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="打開藍牙設備" />

    <Button
        android:id="@+id/close_bluetooth"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="關閉藍牙連接"/>

    <Button
        android:id="@+id/red"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="紅燈" />

    <Button
        android:id="@+id/green"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="綠燈"/>
    <Button
        android:id="@+id/blue"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="藍燈"/>


    <Button
        android:id="@+id/close_all_led"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="關燈"/>



</LinearLayout>

package com.managesoft.nullchen.scm_bluetooth;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;

/**
 * 本地藍牙請求連接目標ble設備,並向其發送數據包
 * 目標設備僅有一盞燈  A B C 不可能同時呈現打開狀態
 * 當燈開啓時  A B C 中僅有一個爲真  其餘兩個爲假
 * 當燈關閉時 A B C  全爲假
 * 數據發送
 * A 請求開啓紅燈
 * B 請求開啓綠燈
 * C 請求開啓藍燈
 * D 請求關閉燈
 *
 */
public class SCM_bluetooth extends AppCompatActivity implements View.OnClickListener{
    private final   Context TAG = SCM_bluetooth.this;
    private final int REQUEST_CODE = 0x001;
    private final String bluetoothAddress = "D8:6C:02:A5:83:DD";
    //設置連接狀態
    private int connect_state = 0;  //未連接
    //設置消息
    private int RED = 'A';
    private int GREEN = 'B';
    private int BLUE = 'C';
    private int ALL_CLOSE = 'D';
    //定義按鈕
    private Button close_all_led;
    private Button red_button;
    private Button green_button;
    private Button blue_button;
    private Button open_bluetooth;
    private Button close_bluetooth;
    // 選中發送數據的藍牙設備,全局變量,否則連接在方法執行完就結束了

    private BluetoothDevice selectDevice = null;
    // UUID,藍牙建立鏈接需要的
    private final UUID MY_UUID = UUID
            .fromString("db764ac8-4b08-7f25-aafe-59d03c27bae3");
    private BluetoothSocket clientSocket;
    // 獲取到向設備寫的輸出流,全局變量,否則連接在方法執行完就結束了
    private OutputStream os;
    BluetoothAdapter mBluetoothAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_scm_bluetooth);
        //初始化按鈕的綁定事件

        //獲取藍牙適配器
         mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        //藍牙的準備工作 1.檢測是否存在本地藍牙
        if(!mBluetoothAdapter.isEnabled()){
            return;
        }
        intitButton();

    }

    private void intitButton() {
        open_bluetooth = (Button)findViewById(R.id.open_bluetooth);
        close_bluetooth = (Button)findViewById(R.id.close_bluetooth);

        red_button = (Button)findViewById(R.id.red);
        green_button = (Button)findViewById(R.id.green);
        blue_button = (Button)findViewById(R.id.blue);
        close_all_led = (Button)findViewById(R.id.close_all_led);
        close_all_led.setOnClickListener(this);
        red_button.setOnClickListener(this);
        green_button.setOnClickListener(this);
        blue_button.setOnClickListener(this);

        open_bluetooth.setOnClickListener(this);
        close_bluetooth.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.open_bluetooth:
                if(mBluetoothAdapter.disable()){
                    startActivityForResult(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE),REQUEST_CODE);
                }else{
                    ShowToast("藍牙已開啓");
                }

                break;
            case R.id.close_bluetooth:
                if(mBluetoothAdapter.enable()){
                    mBluetoothAdapter.disable();
                    ShowToast("正在關閉藍牙...");
                    ShowToast("藍牙已關閉");
                }else {
                    ShowToast("藍牙已關閉");
                }
                break;
            case R.id.red: //點擊紅色按鈕   使得按鈕顏色變紅  其他色爲正常色
                red_button.setBackgroundColor(Color.parseColor("#DC143C"));
                green_button.setBackgroundColor(Color.parseColor("#A9A9A9"));
                blue_button.setBackgroundColor(Color.parseColor("#A9A9A9"));
                ShowToast("RED");
                Send_Msg_SCM(""+'A');
                //此時要求向指定藍牙設備發送信息  A   使得紅燈亮起
                break;
            case R.id.green:
                red_button.setBackgroundColor(Color.parseColor("#A9A9A9"));
                green_button.setBackgroundColor(Color.parseColor("#00FF00"));
                blue_button.setBackgroundColor(Color.parseColor("#A9A9A9"));
                ShowToast("GREEN");
                Send_Msg_SCM(""+'B');
                //此時要求向指定藍牙設備發送信息  B   使得紅燈亮起
                break;
            case R.id.blue:
                red_button.setBackgroundColor(Color.parseColor("#A9A9A9"));
                green_button.setBackgroundColor(Color.parseColor("#A9A9A9"));
                blue_button.setBackgroundColor(Color.parseColor("#4169E1"));
                ShowToast("BLUE");
                Send_Msg_SCM(""+'C');
                //此時要求向指定藍牙設備發送信息  C   使得紅燈亮起
                break;
            case R.id.close_all_led:

                red_button.setBackgroundColor(Color.parseColor("#A9A9A9"));
                green_button.setBackgroundColor(Color.parseColor("#A9A9A9"));
                blue_button.setBackgroundColor(Color.parseColor("#A9A9A9"));
                //此時要求向指定藍牙設備發送信息  D   使得紅燈亮起
                ShowToast("ALL CLOSE");
                Send_Msg_SCM(""+'D');

                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(REQUEST_CODE == requestCode){
            if(requestCode == RESULT_CANCELED){
                ShowToast("藍牙開啓失敗");
            }else {
                ShowToast("藍牙開啓成功");
            }

        }
    }

    //發送消息
    public void Send_Msg_SCM(String Msg){
        if (selectDevice == null) {
            //通過地址獲取到該設備
            selectDevice = mBluetoothAdapter.getRemoteDevice(bluetoothAddress);
        }
        try {
            // 判斷客戶端接口是否爲空
            Log.d("selectDevice",selectDevice+"");
            if (clientSocket == null) {
                // 獲取到客戶端接口
                clientSocket = selectDevice.createRfcommSocketToServiceRecord(MY_UUID);
                // 向服務端發送連接
                Log.d("clientSocket",clientSocket+"");
                clientSocket.connect();
                // 獲取到輸出流,向外寫數據
                os = clientSocket.getOutputStream();

            }
            Log.d("os",os+"");
            // 判斷是否拿到輸出流
            if (os != null) {
                // 需要發送的信息
                //String text = "成功發送信息";
                // 以utf-8的格式發送出去
                String  text = Msg;
                os.write(text.getBytes("UTF-8"));
                ShowToast("發送信息成功");
            }
            // 吐司一下,告訴用戶發送成功
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            // 如果發生異常則告訴用戶發送失敗
            ShowToast("接收方未打開藍牙");
        }

    }

    //吐司 打印
    public void ShowToast(String string){
        Toast toast = Toast.makeText(TAG,string,Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER,0,0);
        toast.show();
    }

}



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