Android下蓝牙4.0 BLE串口模块应用开发

由于APP软件应用环境的需要,我利用蓝牙芯片HC08实现手机和单片机之间的数据通信,工具包括hc-08蓝牙模块一个,电脑一部,安卓手机一部,相关软件:单片机下位机,串口通讯助手等。从官网上下载《汇承HC-08(V3.1)蓝牙4.0 BLE串口模块使用规格书》可以了解蓝牙的相关指令及使用方法。

参考网上的实例,结合自己的业务,我把主要的内容分享如下:

Mainactivity.xm

<RelativeLayout 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"
    >
   <TextView
       android:id="@+id/device_number"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="Devices"
       android:textSize="18dp"
       android:layout_alignParentStart="true" />

   <TextView
       android:id="@+id/location"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_below="@id/device_number"
       android:text="@string/server_location"
       android:textSize="10dp" />
   <Button 
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignParentEnd="true"
       android:text="扫描设备"
       android:id="@+id/scan_dev_btn"
       />

   <ListView
       android:id="@+id/lv"
       android:layout_width="fill_parent"
       android:layout_height="match_parent"
       android:layout_below="@+id/scan_dev_btn"
       android:layout_marginBottom="50dip" >
</ListView>

</RelativeLayout>

Boxactivity.java(安全需要,去掉了部分代码)

package com.blehc08.ui;

import android.app.Activity;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;

import com.blehc08.service.BluetoothLeService;

import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.blehc08.R;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Date;

import static com.blehc08.cFunction.intToHex;
import static com.blehc08.cFunction.intToHexString;

public class Box_Activity extends Activity implements View.OnClickListener {

    private final static String TAG = Ble_Activity.class.getSimpleName();
    public static String HEART_RATE_MEASUREMENT = "0000ffe1-0000-1000-8000-00805f9b34fb";
    public static String EXTRAS_DEVICE_NAME = "DEVICE_NAME";;
    public static String EXTRAS_DEVICE_ADDRESS = "DEVICE_ADDRESS";
    public static String EXTRAS_DEVICE_RSSI = "RSSI";
    //蓝牙连接状态
    private boolean mConnected = false;
    private String status = "disconnected";
    //蓝牙名字
    private String mDeviceName;
    //蓝牙地址
    private String mDeviceAddress;
    //蓝牙信号值
    private String mRssi;
    private Bundle b;
    private String rev_info = ""; //接收到的当前信息
    private String rev_str = "";   //显示当前接收到的信息日志,目的是能够显示每一条指令。

    //蓝牙service,负责后台的蓝牙服务
    private static BluetoothLeService mBluetoothLeService;
    //文本框,显示接受的内容
    private TextView rev_tv, connect_state;

    private String mCommand=""; //发出的指令


    private RadioButton rb_ip1;
    private RadioButton rb_ip2;
    //文本编辑框
    private EditText et_pwd;  //密码输入框
    private ScrollView rev_sv;
    //ip编辑框
    private EditText local_gw_edit_1;
    private EditText local_gw_edit_2;
    private EditText local_gw_edit_3;
    private EditText local_gw_edit_4;
    private EditText local_gw_port;

    private ArrayList<ArrayList<BluetoothGattCharacteristic>> mGattCharacteristics = new ArrayList<ArrayList<BluetoothGattCharacteristic>>();
    //蓝牙特征值
    private static BluetoothGattCharacteristic target_chara = null;
    private Handler mhandler = new Handler();
    private Handler myHandler = new Handler()    {
        // 2.重写消息处理函数
        public void handleMessage(Message msg)
        {
            switch (msg.what)
            {
                // 判断发送的消息
                case 1:
                {
                    // 更新View
                    String state = msg.getData().getString("connect_state");
                    connect_state.setText(state);

                    break;
                }

            }
            super.handleMessage(msg);
        }

    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.box_activity);
        b = getIntent().getExtras();
        //从意图获取显示的蓝牙信息
        mDeviceName = b.getString(EXTRAS_DEVICE_NAME);
        mDeviceAddress = b.getString(EXTRAS_DEVICE_ADDRESS);
        mRssi = b.getString(EXTRAS_DEVICE_RSSI);

        /* 启动蓝牙service */
        Intent gattServiceIntent = new Intent(this, BluetoothLeService.class);
        bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
        init();
    }

    @Override
    protected void onDestroy()    {
        super.onDestroy();
        //解除广播接收器
        unregisterReceiver(mGattUpdateReceiver);
        mBluetoothLeService = null;
    }

    // Activity出来时候,绑定广播接收器,监听蓝牙连接服务传过来的事件
    @Override
    protected void onResume()    {
        super.onResume();
        //绑定广播接收器
        registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
        if (mBluetoothLeService != null)
        {
            //根据蓝牙地址,建立连接
            final boolean result = mBluetoothLeService.connect(mDeviceAddress);
            Log.d(TAG, "Connect request result=" + result);
        }
    }
    private void init() {
        rev_sv = (ScrollView) this.findViewById(R.id.rev_sv);
        rev_tv = (TextView) this.findViewById(R.id.rev_tv);
        connect_state = (TextView) this.findViewById(R.id.connect_state);
        connect_state.setText(status);


        local_gw_edit_1= (EditText) this.findViewById(R.id.local_gw_edit_1);
        local_gw_edit_2= (EditText) this.findViewById(R.id.local_gw_edit_2);
        local_gw_edit_3= (EditText) this.findViewById(R.id.local_gw_edit_3);
        local_gw_edit_4= (EditText) this.findViewById(R.id.local_gw_edit_4);
        local_gw_port= (EditText) this.findViewById(R.id.local_gw_port);

        rb_ip1=(RadioButton) this.findViewById(R.id.rb_ip1);
        rb_ip2=(RadioButton) this.findViewById(R.id.rb_ip2);
        rb_ip1.isChecked();

        et_pwd = (EditText) this.findViewById(R.id.et_pwd);
        btn_getpwd = (Button) this.findViewById(R.id.btn_getpwd);
        btn_getpwd.setOnClickListener(this);

        btn_getip = (Button) this.findViewById(R.id.btn_getip);
        btn_getip.setOnClickListener(this);
        btn_getip.setEnabled(false);

        btn_setip = (Button) this.findViewById(R.id.btn_setip);
        btn_setip.setOnClickListener(this);
        btn_setip.setEnabled(false);


    }
    /* BluetoothLeService绑定的回调函数 */
    private final ServiceConnection mServiceConnection = new ServiceConnection()    {

        @Override
        public void onServiceConnected(ComponentName componentName,
                                       IBinder service)
        {
            mBluetoothLeService = ((BluetoothLeService.LocalBinder) service)
                    .getService();
            if (!mBluetoothLeService.initialize())
            {
                Log.e(TAG, "Unable to initialize Bluetooth");
                finish();
            }
            // Automatically connects to the device upon successful start-up
            // initialization.
            // 根据蓝牙地址,连接设备
            mBluetoothLeService.connect(mDeviceAddress);

        }

        @Override
        public void onServiceDisconnected(ComponentName componentName)
        {
            mBluetoothLeService = null;
        }

    };

    /**
     * 广播接收器,负责接收BluetoothLeService类发送的数据
     */
    private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver()
    {
        @Override
        public void onReceive(Context context, Intent intent)
        {
            final String action = intent.getAction();
            if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action))//Gatt连接成功
            {
                mConnected = true;
                status = "connected";
                //更新连接状态
                updateConnectionState(status);
         
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

消灭倭寇

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值