android 蓝牙2.0 demo4.0和2.0兼容吗

很多 android 手机宣称支持蓝牙 4.0,但不能和其它支持蓝牙 4.0 的设备交换数据,如何解决
全部答案(共4个回答)
互传,比如快牙
可以连接的
答:当然能连接,耳机的传输速度要求不高的,所以蓝牙4.0标准和蓝牙3.0标准的耳机用你的耳朵来听,效果一样!实际上因为耳机是蓝牙3.0标准的,所以蓝牙4.0标准...
这个是支持和fitbit flex同步的啊如果能帮到你,麻烦点击“有用”,谢谢!
如果是官方直接升级是4.0,理论是没问题的,只是习惯问题。
如果网上下载的所谓4.0升级包ROM,建议暂时不要刷。
设置-手机信息-蓝牙版本,目前主流手机的蓝牙版本皆在2.0左右!~如果再不可以就安装个Android感应器查看啊!希望可以帮到你!记得给好评噢!
答: 金融@家怎么在手机上用
答: 您好,这个直接输入账号就可以了!
答: 主流手机配置,不错的一个选择。
答: 中关村在线可以
大家还关注
Copyright &
Corporation, All Rights Reserved
确定举报此问题
举报原因(必选):
广告或垃圾信息
激进时政或意识形态话题
不雅词句或人身攻击
侵犯他人隐私
其它违法和不良信息
报告,这不是个问题
报告原因(必选):
这不是个问题
这个问题分类似乎错了
这个不是我熟悉的地区
相关问答:123456789101112131415如何让Android 蓝牙APP,同时支持连接蓝牙4.0模块和2.0模块。_百度知道
如何让Android 蓝牙APP,同时支持连接蓝牙4.0模块和2.0模块。
己写了个Android 蓝牙APP.0模块,但2.0模块能够搜素到,可以连接蓝牙4
我有更好的答案
支持蓝牙4.0的都可以兼容2.0的模块。蓝牙2.0与4.0最主要的区别就是蓝牙2.0的传输速度没有蓝牙4.0快。以下为蓝牙各版本的说明:1.1&为最早期版本,传输率约在748~810kb/s,因是早期设计,容易受到同频率之产品所干扰下影响通讯质量。蓝牙1.2标准1.2&同样是只有&748~810kb/s&的传输率,但在加上了(改善&Software)抗干扰跳频功能。蓝牙2.0标准2.0&是&1.2&的改良提升版,传输率约在&1.8M/s~2.1M/s,开始支持双工模式——即一面作语音通讯,同时亦可以传输档案/高质素图片,2.0&版本当然也支持&Stereo&运作。应用最为广泛的是Bluetooth&2.0+EDR标准,该标准在2004年已经推出,支持Bluetooth&2.0+EDR标准的产品也于2006年大量出现。虽然Bluetooth&2.0+EDR标准在技术上作了大量的改进,但从1.X标准延续下来的配置流程复杂和设备功耗较大的问题依然存在。蓝牙2.1标准日,蓝牙技术联盟今天正式批准了蓝牙2.1版规范,即“蓝牙2.1+EDR”,可供未来的设备自由使用。和2.0版本同时代产品,目前仍然占据蓝牙市场较大份额,相对2.0版本主要是提高了待机时间2倍以上,技术标准没有根本性变化。蓝牙3.0标准日,蓝牙技术联盟(Bluetooth&SIG)正式颁布了新一代标准规范&Bluetooth&Core&Specification&Version&3.0&High&Speed&(蓝牙核心规范3.0版&),蓝牙3.0的核心是&Generic&Alternate&MAC/PHY&(AMP),这是一种全新的交替射频技术,允许蓝牙协议栈针对任一任务动态地选择正确射频。蓝牙3.0的数据传输率提高到了大约24Mbps(即可在需要的时候调用802.11&WI-FI用于实现高速数据传输)。在传输速度上,蓝牙3.0是蓝牙2.0的八倍,可以轻松用于录像机至高清电视、PC至PMP、UMPC至打印机之间的资料传输,但是需要双方都达到此标准才能实现功能。蓝牙4.0标准蓝牙4.0规范于日正式发布,新版本的最大意义在于低功耗,同时加强不同OEM厂商之间的设备兼容性,并且降低延迟,理论最高传输速度依然为24Mbps(即3MB/s),有效覆盖范围扩大到100米(之前的版本为10米)。该标准芯片被大量的手机、平板所采用,如苹果The&New&iPad平板电脑,以及苹果iPhone&5、魅族MX4、HTC&One&X等手机上带有蓝牙4.0功能。蓝牙4.1标准蓝牙4.1于日发布,与LTE无线电信号之间如果同时传输数据,那么蓝牙4.1可以自动协调两者的传输信息,理论上可以减少&其它信号对蓝牙4.1的干扰。改进是提升了连接速度并且更加智能化,比如减少了设备之间重新连接的时间,意味着用户如果走出了蓝牙4.1的信号范围并且断开连接的时间不算很长,当用户再次回到信号范围中之后设备将自动连接,反应时间要比蓝牙4.0更短。最后一个改进之处是提高传输效率,如果用户连接的设备&非常多,比如连接了多部可穿戴设备,彼此之间的信息都能即时发送到接接收设备上。除此之外,蓝牙4.1也为开发人员增加了更多的灵活性,这个改变对普通用户没有很大影响,但是对于软件开发者来说是很重要的,因为为了应对逐渐兴起的可穿戴设备,那么蓝牙必须能够支持同时连接多部设备。目前支持该标准的手机还比较少,三星GALAXY&Note4则是其中具有代表性的一款。蓝牙4.2标准日,最新的蓝牙4.2标准颁布,改善了数据传输速度和隐私保护程度,并接入了该设备将可直接通过IPv6和6LoWPAN接入互联网。在新的标准下蓝牙信号想要连接或者追踪用户设备必须经过用户许可,否则蓝牙信号将无法连接和追踪用户设备。速度方面变得更加快速,两部蓝牙设备之间的数据传输速度提高了2.5倍,因为蓝牙智能(Bluetooth&Smart)数据包的容量提高,其可容纳的数据量相当于此前的10倍左右。蓝牙的版本自然是越高级越好,考虑到传输距离和功耗的问题,最新的蓝牙4.1是优选,但是目前市场上蓝牙4.1的产品并不多,而主流的蓝牙4.0产品性价比更高,至于蓝牙3.0、2.1及以下的版本已经失去选购的价值。
看哥的,就OK啦你会发现你们安装两个蓝牙app?不可能,下载安卓apk编辑器,有破解的自己搜,第二,第三,选择它弹出选项,选择制作共存同时支持是不可能滴,一个蓝牙app只能有一个版本.0要么4.0
除非你有两个蓝牙,什么,不过手机支不支持,俺就不知道咯,要么2!第一步,打开并在里面找到你编写的蓝牙app
看来是遇到行家了。再请教一下,考虑到蓝牙模块4.0兼容2.0,如果让APP仅仅支持2.0连接,如何操作?
兄弟,4.0要是兼容2.0的话,你还玩儿个毛啊,这问题白问了都
难道你想让低阶app升级?
自己专门针对2.0写一个算了,制作共存后再修改成4.0的
本回答被网友采纳
只能连一个
为您推荐:
其他类似问题
android的相关知识
换一换
回答问题,赢新手礼包
个人、企业类
违法有害信息,请在下方选择后提交
色情、暴力
我们会通过消息、邮箱等方式尽快将举报结果通知您。当前位置 & &
& Android+蓝牙 4.0 将带来什么?
Android+蓝牙 4.0 将带来什么?
14:53:33&&出处:&&
编辑:鲲鹏 &&)
让小伙伴们也看看:
阅读更多:
好文共享:
文章观点支持
文章价值打分
当前文章打分0 分,共有0人打分
[04-04][04-04][04-04][04-03][04-02][04-02][04-02][04-02][04-02][04-02]
登录驱动之家
没有帐号?
用合作网站帐户直接登录Android蓝牙串口通讯(1)
1.嗯有段时间没更新博客啦,给广大CSDN友上点干活
2.android蓝牙即智能穿戴设备火起来之后蓝牙的普及也是有点猛,今天我们博客的主题就是围绕arduino开发蓝牙控制小车写的测试demo,连接的蓝牙模块是HC-08,06型号,所以出厂的硬件UUID是厂商提供的,增对该demo用的范围也是有限的,当前蓝牙的开发功能和库的使用基本都是一样的,不一样的只是硬件蓝牙模块的UUID,假如想做智能手环什么的换成手环的蓝牙UUID就可以用,嗯,就是这么简单
3.下面先上个gif图爽爽看看效果先,本人基本都是先看效果再决定是否下载该demo
由于我的网络不是很好用的远程投屏至电脑才录制的gif所以看起来搜索蓝牙有点卡,实际效果是不卡的,中间出现的警告框是楼主的手机后台内存只有600+M所以有一个实时监测手机内存的,防止内存不足demo崩了,嗯,个人感觉还是不错的
4.下面上主要代码截图:MainActivity
package com.example.
import java.io.IOE
import java.io.InputS
import java.io.OutputS
import java.lang.reflect.M
import java.util.ArrayL
import java.util.C
import java.util.HashM
import java.util.L
import java.util.M
import java.util.S
import java.util.UUID;
import com.baoyz.swipemenulistview.SwipeM
import com.baoyz.swipemenulistview.SwipeMenuC
import com.baoyz.swipemenulistview.SwipeMenuI
import com.baoyz.swipemenulistview.SwipeMenuListV
import com.baoyz.swipemenulistview.SwipeMenuListView.OnMenuItemClickL
import android.app.A
import android.app.ActivityM
import android.app.D
import android.bluetooth.BluetoothA
import android.bluetooth.BluetoothD
import android.bluetooth.BluetoothGattC
import android.bluetooth.BluetoothGattD
import android.bluetooth.BluetoothGattS
import android.bluetooth.BluetoothM
import android.bluetooth.BluetoothS
import android.content.BroadcastR
import android.content.ComponentN
import android.content.C
import android.content.I
import android.content.IntentF
import android.content.ServiceC
import android.content.pm.PackageM
import android.graphics.C
import android.graphics.drawable.ColorD
import android.os.B
import android.os.H
import android.os.IB
import android.os.M
import android.util.L
import android.util.TypedV
import android.view.M
import android.view.MenuI
import android.view.MotionE
import android.view.V
import android.view.View.OnClickL
import android.view.View.OnTouchL
import android.view.inputmethod.InputMethodM
import android.widget.AdapterV
import android.widget.B
import android.widget.EditT
import android.widget.ListV
import android.widget.TextV
import android.widget.T
import android.widget.AdapterView.OnItemClickL
public class MainActivity extends Activity implements OnClickListener, OnItemClickListener {
protected static final String TAG = "MainActivity";
// 扫描、断开、发送蓝牙button
private Button btn_scan_device, btn_disconnect, btn_
// 未配对蓝牙的listview
private ListView lv_disconnect, listview_
// 已配对蓝牙的listview,自定义的listview带滑动删除
private SwipeMenuListView lv_
// 输入数据的edittext
private EditText ed_
private int REQUEST_ENABLE_BT = 1;
private List&String& list = new ArrayList&String&();
private ConnectThread mConnectT
public ConnectedThread mConnectedT
private Dialog progressD
private TextV
// 蓝牙适配器
private BluetoothAdapter mBluetoothA
// 已经配对的蓝牙ArrayList
private ArrayList&BluetoothDevice& data_connect = new ArrayList&BluetoothDevice&();
// 未配对的蓝牙ArrayList
private ArrayList&BluetoothDevice& data_disconnect = new ArrayList&BluetoothDevice&();
// 自定义的adapater,已经配对的蓝牙,未配对的蓝牙
private LeDeviceListAdapter connectListAdapter, disconnectListA
// HC-08蓝牙连接状态
private boolean mConnected =
// HC-06蓝牙连接状态
private boolean mhc06Connected =
// 连接成功的蓝牙名字
private String connect_
// 未配对的HC-06,08点击的标记位
private int data_onitemclick, datahc06_
// HC-06:判断是已经配对的蓝牙还是未配对的蓝牙,断开连接的视图更新
private boolean disconnect_flag =
// HC-08蓝牙地址
private String mDeviceA
// 蓝牙设备
private BluetoothDevice dataconnectB
// 蓝牙service,负责后台的蓝牙服务
private static BluetoothLeService mBluetoothLeS
// 蓝牙的连接状态
private String status = "disconnected";
// 蓝牙特征值
private static BluetoothGattCharacteristic target_chara =
private ArrayList&ArrayList&BluetoothGattCharacteristic&& mGattCharacteristics = new ArrayList&ArrayList&BluetoothGattCharacteristic&&();
// 蓝牙4.0的UUID,其中0000ffe1-00-fb是广州汇承信息科技有限公司08蓝牙模块的UUID
public static String HEART_RATE_MEASUREMENT = "0000ffe1-00-fb";
// HC-06蓝牙UUID
private static final String SPP_UUID = "0-805F9B34FB";
private List&Integer& mBuffer = new ArrayList&Integer&();
private List&ChatMsgEntity& mDataArrays = new ArrayList&ChatMsgEntity&();
private ChatMsgViewAdapter mA
private SelfDialog selfD
private Handler mhandler = new Handler();
private Handler myHandler = new Handler() {
// 2.重写消息处理函数
public void handleMessage(Message msg) {
switch (msg.what) {
// 判断发送的消息
// 更新View
if (mConnected == true) {
String state = msg.getData().getString("connect_state");
setTitle(connect_string + ":" + state);
String state = msg.getData().getString("connect_state");
setTitle(state);
// 更新View
if (mhc06Connected == true) {
String state = msg.getData().getString("connect_state");
setTitle(connect_string + ":" + state);
data_connect.add(data_disconnect.get(datahc06_onitemclick));
data_disconnect.remove(datahc06_onitemclick);
disconnectListAdapter = new LeDeviceListAdapter(MainActivity.this, data_disconnect);
// 为listview指定适配器
lv_disconnect.setAdapter(disconnectListAdapter);
disconnectListAdapter.notifyDataSetChanged();
connectListAdapter = new LeDeviceListAdapter(MainActivity.this, data_connect);
// 为listview指定适配器
lv_connect.setAdapter(connectListAdapter);
connectListAdapter.notifyDataSetChanged();
String state = msg.getData().getString("connect_state");
setTitle(state);
// 更新View
if (mhc06Connected == true) {
String state = msg.getData().getString("connect_state");
setTitle(connect_string + ":" + state);
String state = msg.getData().getString("connect_state");
setTitle(state);
String state = msg.getData().getString("updata_msg");
listview_msg_stringReceiver(new String(state));
super.handleMessage(msg);
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_scan_device = (Button) findViewById(R.id.btn_scandevice);
btn_disconnect = (Button) findViewById(R.id.btn_disconnectdevice);
ed_inout = (EditText) findViewById(R.id.ed_inout);
btn_send = (Button) findViewById(R.id.btn_send);
lv_connect = (SwipeMenuListView) findViewById(R.id.lv_connect);
lv_disconnect = (ListView) findViewById(R.id.lv_disconnect);
listview_msgxianshi = (ListView) findViewById(R.id.listView1);
btn_scan_device.setOnClickListener(this);
btn_disconnect.setOnClickListener(this);
btn_send.setOnClickListener(this);
lv_disconnect.setOnItemClickListener(this);
lv_connect.setOnItemClickListener(this);
// mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
// 打开蓝牙权限
if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
Set&BluetoothDevice& pairedDevices = mBluetoothAdapter.getBondedDevices();
if (pairedDevices.size() & 0) {
for (BluetoothDevice device : pairedDevices) {
// DeviceBean bean = new DeviceBean();
// bean.setAddress(device.getAddress());
// bean.setName(device.getName());
data_connect.add(device);
// unpairDevice(device);
Toast.makeText(MainActivity.this, "没有已配对的设备", Toast.LENGTH_SHORT).show();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(mReceiver, filter);
// Register for broadcasts when discovery has finished
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(mReceiver, filter);
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
msgDialog("您的手机系统低于4.3,不支持ble4.0蓝牙");
msgDialog("您的手机系统高于4.3,支持ble4.0蓝牙");
connectListAdapter = new LeDeviceListAdapter(MainActivity.this, data_connect);
// 为listview指定适配器
lv_connect.setAdapter(connectListAdapter);
disconnectListAdapter = new LeDeviceListAdapter(MainActivity.this, data_disconnect);
// 为listview指定适配器
lv_disconnect.setAdapter(disconnectListAdapter);
/* 启动蓝牙service */
Intent gattServiceIntent = new Intent(this, BluetoothLeService.class);
bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
// 绑定广播接收器
registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
progressDialog = new Dialog(MainActivity.this, R.style.progress_dialog);
progressDialog.setContentView(R.layout.dialog);
progressDialog.setCancelable(true);
progressDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
msg = (TextView) progressDialog.findViewById(R.id.id_tv_loadingmsg);
progressDialog.setCanceledOnTouchOutside(false);
SwipeMenuCreator creator = new SwipeMenuCreator() {
public void create(SwipeMenu menu) {
// create "open" item
SwipeMenuItem openItem = new SwipeMenuItem(getApplicationContext());
// set item background
openItem.setBackground(new ColorDrawable(Color.rgb(0xC9, 0xC9, 0xCE)));
// set item width
openItem.setWidth(dp2px(90));
// set item title
openItem.setTitle("取消配对");
// set item title fontsize
openItem.setTitleSize(14);
// set item title font color
openItem.setTitleColor(Color.WHITE);
// add to menu
menu.addMenuItem(openItem);
// set creator
lv_connect.setMenuCreator(creator);
// step 2. listener item click event
lv_connect.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public void onMenuItemClick(int position, SwipeMenu menu, int index) {
if (data_connect.get(position).getName().equals("HC-06")) {
if_or_notPair();
unpairDevice(data_connect.get(position));
data_connect.remove(position);
connectListAdapter.notifyDataSetChanged();
Toast.makeText(MainActivity.this, "HC-06支持取消配对,别的蓝牙设备无法消配对", Toast.LENGTH_SHORT).show();
mAdapter = new ChatMsgViewAdapter(getApplicationContext(), mDataArrays);
listview_msgxianshi.setAdapter(mAdapter);
listview_msgxianshi.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(
getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
// 取消已经配对的蓝牙(HC-06)
private void unpairDevice(BluetoothDevice device) {
Method m = device.getClass().getMethod("removeBond", (Class[]) null);
m.invoke(device, (Object[]) null);
} catch (Exception e) {
Log.e(TAG, e.getMessage());
private void msgDialog(String string) {
selfDialog = new SelfDialog(MainActivity.this);
selfDialog.setTitle("提示");
selfDialog.setMessage(string);
selfDialog.setYesOnclickListener("确定", new SelfDialog.onYesOnclickListener() {
public void onYesClick() {
// Toast.makeText(MainActivity.this,"点击了--确定--按钮",Toast.LENGTH_LONG).show();
selfDialog.dismiss();
selfDialog.setNoOnclickListener("取消", new SelfDialog.onNoOnclickListener() {
public void onNoClick() {
// Toast.makeText(MainActivity.this,"点击了--取消--按钮",Toast.LENGTH_LONG).show();
selfDialog.dismiss();
selfDialog.show();
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return super.onOptionsItemSelected(item);
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_scandevice:
btn_scan_device.setEnabled(false);
msg.setText("卖力加载中");
progressDialog.show();
doDiscovery();
case R.id.btn_disconnectdevice:
if (mConnected == true) {
mBluetoothLeService.disconnect();
for (int i = 0; i & data_connect.size(); i++) {
if (data_connect.get(i).equals(dataconnectBean)) {
data_disconnect.add(data_connect.get(i));
data_connect.remove(i);
connectListAdapter = new LeDeviceListAdapter(MainActivity.this, data_connect);
// 为listview指定适配器
lv_connect.setAdapter(connectListAdapter);
connectListAdapter.notifyDataSetChanged();
disconnectListAdapter = new LeDeviceListAdapter(MainActivity.this, data_disconnect);
// 为listview指定适配器
lv_disconnect.setAdapter(disconnectListAdapter);
disconnectListAdapter.notifyDataSetChanged();
if_or_notPair();
case R.id.btn_send:
if (mConnected == false) {
if (ed_inout.getText().toString().equals("")) {
Log.d(TAG, "111111");
if(isServiceRunning(getApplicationContext(), "com.example.androidbluetooch.BluetoothLeService")==true){
Toast.makeText(getApplicationContext(), "存在", Toast.LENGTH_SHORT).show();
if(target_chara==null){
Log.d(TAG, "222222");
target_chara.setValue(ed_inout.getText().toString());
// 调用蓝牙服务的写特征值方法实现发送数据
mBluetoothLeService.writeCharacteristic(target_chara);
listview_msg_stringSend();
msgDialog("运行当前所需的服务没有起来,请至应用管理释放点内存,以保证当前APP所需的运行内存");
if (mhc06Connected == true) {
if (ed_inout != null && !"".equals(ed_inout)) {
mConnectedThread.write(ed_inout.getText().toString().getBytes());
listview_msg_stringSend();
} catch (Exception e) {
if(mConnected==false||mhc06Connected==false){
listview_msg_stringSend();
ed_inout.setText("");
private String getDate() {
Calendar c = Calendar.getInstance();
String year = String.valueOf(c.get(Calendar.YEAR));
String month = String.valueOf(c.get(Calendar.MONTH)+ 1);
String day = String.valueOf(c.get(Calendar.DAY_OF_MONTH));
String hour = String.valueOf(c.get(Calendar.HOUR_OF_DAY));
String mins = String.valueOf(c.get(Calendar.MINUTE));
StringBuffer sbBuffer = new StringBuffer();
sbBuffer.append(year + "-" + month + "-" + day + " " + hour + ":" + mins);
return sbBuffer.toString();
private void listview_msg_stringSend() {
* 发送消息跟新View
ChatMsgEntity entity = new ChatMsgEntity();
entity.setDate(getDate());
entity.setName("user");
entity.setMsgType(false);
entity.setText(ed_inout.getText().toString());
mDataArrays.add(entity);
mAdapter.notifyDataSetChanged();
ed_inout.setText("");
listview_msgxianshi.setSelection(listview_msgxianshi.getCount() - 1);
private void listview_msg_stringReceiver(String string) {
* 接收消息跟新View
ChatMsgEntity entity = new ChatMsgEntity();
entity.setDate(getDate());
entity.setName("设备");
entity.setMsgType(true);
entity.setText(string);
mDataArrays.add(entity);
mAdapter.notifyDataSetChanged();
listview_msgxianshi.setSelection(listview_msgxianshi.getCount() - 1);
private void if_or_notPair() {
if (disconnect_flag == true) {
if (mhc06Connected == true) {
if (mConnectThread != null) {
mConnectThread.cancel();
mConnectThread =
if (mConnectedThread != null) {
mConnectedThread.cancel();
mConnectedThread =
mhc06Connected =
status = "disconnected";
// 更新连接状态
Message msg1 = new Message();
msg1.what = 3;
Bundle b = new Bundle();
b.putString("connect_state", status);
msg1.setData(b);
// 将连接状态更新的UI的textview上
myHandler.sendMessage(msg1);
if (mhc06Connected == true) {
if (mConnectThread != null) {
mConnectThread.cancel();
mConnectThread =
if (mConnectedThread != null) {
mConnectedThread.cancel();
mConnectedThread =
mhc06Connected =
status = "disconnected";
// 更新连接状态
Message msg2 = new Message();
msg2.what = 2;
Bundle b = new Bundle();
b.putString("connect_state", status);
msg2.setData(b);
// 将连接状态更新的UI的textview上
myHandler.sendMessage(msg2);
// 搜索蓝牙
private void doDiscovery() {
setTitle(R.string.scanning);
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
mBluetoothAdapter.startDiscovery();
// 搜索蓝牙的广播
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// If it's already paired, skip it, because it's been listed
// already
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
// mNewDevicesArrayAdapter.add(device.getName() + "\n" +
// device.getAddress());
if (list.indexOf(device.getAddress().toString()) == -1) {
Map&String, Object& listem = new HashMap&String, Object&();
listem.put("dName", device.getName());
listem.put("dAddress", device.getAddress().toString());
Log.d("searchBtDevices==", list.toString());
list.add(device.getAddress());
Log.d("searchBtDevices==", list.toString());
Log.d("Devices==", device.getAddress());
Log.d("==", "not");
// DeviceBean bean = new DeviceBean();
// bean.setAddress(device.getAddress());
// bean.setName(device.getName());
data_disconnect.add(device);
disconnectListAdapter = new LeDeviceListAdapter(MainActivity.this, data_disconnect);
// 为listview指定适配器
lv_disconnect.setAdapter(disconnectListAdapter);
disconnectListAdapter.notifyDataSetChanged();
Log.d("==", "have");
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
btn_scan_device.setEnabled(true);
progressDialog.dismiss();
setTitle(R.string.select_device);
/* BluetoothLeService绑定的回调函数 */
private final ServiceConnection mServiceConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName componentName, IBinder service) {
mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
if (!mBluetoothLeService.initialize()) {
Log.e("MainActivity.this", "Unable to initialize Bluetooth");
// Automatically connects to the device upon successful start-up
// initialization.
// 根据蓝牙地址,连接设备
// 每次连接之前关闭上一次连接,这样在第二次连接蓝牙的时候速度快
// 博客参考http://bbs.eeworld.com.cn/thread--1.html
mBluetoothLeService.close();
mBluetoothLeService.connect(mDeviceAddress);
public void onServiceDisconnected(ComponentName componentName) {
mBluetoothLeService =
* 广播接收器,负责接收BluetoothLeService类发送的数据
private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action))// Gatt连接成功
progressDialog.dismiss();
mConnected =
status = "connected";
// 更新连接状态
updateConnectionState(status);
System.out.println("BroadcastReceiver :" + "device connected");
data_connect.add(data_disconnect.get(data_onitemclick));
data_disconnect.remove(data_onitemclick);
disconnectListAdapter = new LeDeviceListAdapter(MainActivity.this, data_disconnect);
// 为listview指定适配器
lv_disconnect.setAdapter(disconnectListAdapter);
disconnectListAdapter.notifyDataSetChanged();
connectListAdapter = new LeDeviceListAdapter(MainActivity.this, data_connect);
// 为listview指定适配器
lv_connect.setAdapter(connectListAdapter);
connectListAdapter.notifyDataSetChanged();
} else if (BluetoothLeService.ACTION_GATT_DISCONNECTED// Gatt连接失败
.equals(action)) {
progressDialog.dismiss();
mConnected =
status = "disconnected";
// 更新连接状态
updateConnectionState(status);
System.out.println("BroadcastReceiver :" + "device disconnected");
for (int i = 0; i & data_connect.size(); i++) {
if (data_connect.get(i).equals(dataconnectBean)) {
data_disconnect.add(data_connect.get(i));
data_connect.remove(i);
connectListAdapter = new LeDeviceListAdapter(MainActivity.this, data_connect);
// 为listview指定适配器
lv_connect.setAdapter(connectListAdapter);
connectListAdapter.notifyDataSetChanged();
disconnectListAdapter = new LeDeviceListAdapter(MainActivity.this, data_disconnect);
// 为listview指定适配器
lv_disconnect.setAdapter(disconnectListAdapter);
disconnectListAdapter.notifyDataSetChanged();
} else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED// 发现GATT服务器
.equals(action)) {
// Show all the supported services and characteristics on the
// user interface.
// 获取设备的所有蓝牙服务
displayGattServices(mBluetoothLeService.getSupportedGattServices());
System.out.println("BroadcastReceiver :" + "device SERVICES_DISCOVERED");
} else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {// 有效数据
// 处理发送过来的数据
Log.d(TAG, intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
listview_msg_stringReceiver(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
/* 更新连接状态 */
private void updateConnectionState(String status) {
Message msg = new Message();
msg.what = 1;
Bundle b = new Bundle();
b.putString("connect_state", status);
msg.setData(b);
// 将连接状态更新的UI的textview上
myHandler.sendMessage(msg);
System.out.println("connect_state:" + status);
* @Title: displayGattServices @Description: TODO(处理蓝牙服务) @param 无 @return
void @throws
private void displayGattServices(List&BluetoothGattService& gattServices) {
if (gattServices == null)
String uuid =
// 服务数据,可扩展下拉列表的第一级数据
ArrayList&HashMap&String, String&& gattServiceData = new ArrayList&HashMap&String, String&&();
// 特征数据(隶属于某一级服务下面的特征值集合)
ArrayList&ArrayList&HashMap&String, String&&& gattCharacteristicData = new ArrayList&ArrayList&HashMap&String, String&&&();
// 部分层次,所有特征值集合
mGattCharacteristics = new ArrayList&ArrayList&BluetoothGattCharacteristic&&();
// Loops through available GATT Services.
for (BluetoothGattService gattService : gattServices) {
// 获取服务列表
HashMap&String, String& currentServiceData = new HashMap&String, String&();
uuid = gattService.getUuid().toString();
// 查表,根据该uuid获取对应的服务名称。SampleGattAttributes这个表需要自定义。
gattServiceData.add(currentServiceData);
System.out.println("Service uuid:" + uuid);
ArrayList&HashMap&String, String&& gattCharacteristicGroupData = new ArrayList&HashMap&String, String&&();
// 从当前循环所指向的服务中读取特征值列表
List&BluetoothGattCharacteristic& gattCharacteristics = gattService.getCharacteristics();
ArrayList&BluetoothGattCharacteristic& charas = new ArrayList&BluetoothGattCharacteristic&();
// Loops through available Characteristics.
// 对于当前循环所指向的服务中的每一个特征值
for (final BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
charas.add(gattCharacteristic);
HashMap&String, String& currentCharaData = new HashMap&String, String&();
uuid = gattCharacteristic.getUuid().toString();
if (gattCharacteristic.getUuid().toString().equals(HEART_RATE_MEASUREMENT)) {
// 测试读取当前Characteristic数据,会触发mOnDataAvailable.onCharacteristicRead()
mhandler.postDelayed(new Runnable() {
public void run() {
mBluetoothLeService.readCharacteristic(gattCharacteristic);
// 接受Characteristic被写的通知,收到蓝牙模块的数据后会触发mOnDataAvailable.onCharacteristicWrite()
mBluetoothLeService.setCharacteristicNotification(gattCharacteristic, true);
target_chara = gattC
// 设置数据内容
// 往蓝牙模块写入数据
// mBluetoothLeService.writeCharacteristic(gattCharacteristic);
List&BluetoothGattDescriptor& descriptors = gattCharacteristic.getDescriptors();
for (BluetoothGattDescriptor descriptor : descriptors) {
System.out.println("---descriptor UUID:" + descriptor.getUuid());
// 获取特征值的描述
mBluetoothLeService.getCharacteristicDescriptor(descriptor);
// mBluetoothLeService.setCharacteristicNotification(gattCharacteristic,
gattCharacteristicGroupData.add(currentCharaData);
// 按先后顺序,分层次放入特征值集合中,只有特征值
mGattCharacteristics.add(charas);
// 构件第二级扩展列表(服务下面的特征值)
gattCharacteristicData.add(gattCharacteristicGroupData);
/* 意图过滤器 */
private static IntentFilter makeGattUpdateIntentFilter() {
final IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
return intentF
// HC-06蓝牙的连接方法
public void connect(BluetoothDevice device) {
Log.d(TAG, "connect to: " + device);
// Start the thread to connect with the given device
mConnectThread = new ConnectThread(device);
mConnectThread.start();
* This thread runs while attempting to make an outgoing connection with a
* device. It r the connection either succeeds or
// HC-06蓝牙的连接方法
private class ConnectThread extends Thread {
private final BluetoothSocket mmS
public ConnectThread(BluetoothDevice device) {
BluetoothSocket tmp =
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
tmp = device.createRfcommSocketToServiceRecord(UUID.fromString(SPP_UUID));
} catch (IOException e) {
Log.e(TAG, "create() failed", e);
mmSocket =
public void run() {
Log.i(TAG, "BEGIN mConnectThread");
setName("ConnectThread");
// Always cancel discovery because it will slow down a connection
mBluetoothAdapter.cancelDiscovery();
// Make a connection to the BluetoothSocket
// This is a blocking call and will only return on a
// successful connection or an exception
mmSocket.connect();
} catch (IOException e) {
progressDialog.dismiss();
Log.e(TAG, "unable to connect() socket", e);
// Close the socket
mmSocket.close();
} catch (IOException e2) {
Log.e(TAG, "unable to close() socket during connection failure", e2);
mConnectThread =
progressDialog.dismiss();
if (disconnect_flag == true) {
mhc06Connected =
status = "connected";
// 更新连接状态
Message msg = new Message();
msg.what = 3;
Bundle b = new Bundle();
b.putString("connect_state", status);
msg.setData(b);
// 将连接状态更新的UI的textview上
myHandler.sendMessage(msg);
mhc06Connected =
status = "connected";
// 更新连接状态
Message msg = new Message();
msg.what = 2;
Bundle b = new Bundle();
b.putString("connect_state", status);
msg.setData(b);
// 将连接状态更新的UI的textview上
myHandler.sendMessage(msg);
// Start the connected thread
// Start the thread to manage the connection and perform
// transmissions
mConnectedThread = new ConnectedThread(mmSocket);
mConnectedThread.start();
public void cancel() {
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "close() of connect socket failed", e);
* This thread runs during a connection with a remote device. It handles all
* incoming and outgoing transmissions.
// HC-06蓝牙的连接方法
private class ConnectedThread extends Thread {
private final BluetoothSocket mmS
private final InputStream mmInS
private final OutputStream mmOutS
public ConnectedThread(BluetoothSocket socket) {
Log.d(TAG, "create ConnectedThread");
mmSocket =
InputStream tmpIn =
OutputStream tmpOut =
// Get the BluetoothSocket input and output streams
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
Log.e(TAG, "temp sockets not created", e);
mmInStream = tmpIn;
mmOutStream = tmpO
public void run() {
Log.i(TAG, "BEGIN mConnectedThread");
byte[] buffer = new byte[256];
// Keep listening to the InputStream while connected
while (true) {
// //HC-06蓝牙的读数据方法
bytes = mmInStream.read(buffer);
Log.d(TAG, "" + new String(buffer));
Message msg1 = new Message();
msg1.what = 4;
Bundle b = new Bundle();
b.putString("updata_msg", new String(buffer));
msg1.setData(b);
// 将连接状态更新的UI的textview上
myHandler.sendMessage(msg1);
synchronized (mBuffer) {
for (int i = 0; i & i++) {
mBuffer.add(buffer[i] & 0xFF);
// mHandler.sendEmptyMessage(MSG_NEW_DATA);
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
* Write to the connected OutStream.
* @param buffer
The bytes to write
// HC-06蓝牙的写数据方法
public void write(byte[] buffer) {
mmOutStream.write(buffer);
} catch (IOException e) {
Log.e(TAG, "Exception during write", e);
public void cancel() {
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "close() of connect socket failed", e);
private int dp2px(int dp) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics());
public void onItemClick(AdapterView&?& arg0, View arg1, int position, long arg3) {
switch (arg0.getId()) {
// 已经配对的蓝牙点击事件
case R.id.lv_connect:
if (mConnected == true || mhc06Connected == true) {
Toast.makeText(MainActivity.this, "请先断开当前连接", Toast.LENGTH_SHORT).show();
if (data_connect.get(position).getName().equals("HC-06")) {
msg.setText("连接蓝牙中");
progressDialog.show();
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(data_connect.get(position).getAddress());
// Attempt to connect to the device
connect(device);
connect_string = data_connect.get(position).getName();
datahc06_onitemclick =
disconnect_flag =
Toast.makeText(getApplicationContext(), "该功能只支持连接HC-06,08蓝牙模块", Toast.LENGTH_SHORT).show();
// 未配对的蓝牙点击事件
case R.id.lv_disconnect:
if (mConnected == true || mhc06Connected == true) {
Toast.makeText(MainActivity.this, "请先断开当前连接", Toast.LENGTH_SHORT).show();
if (data_disconnect.get(position).getName().equals("HC-08")) {
msg.setText("连接蓝牙中");
progressDialog.show();
data_onitemclick =
dataconnectBean = data_disconnect.get(position);
mDeviceAddress = data_disconnect.get(position).getAddress();
Log.d(TAG, "111" + data_disconnect.get(position).getAddress());
if (mBluetoothLeService != null) {
// 每次连接之前关闭上一次连接,这样在第二次连接蓝牙的时候速度快
// 博客参考http://bbs.eeworld.com.cn/thread--1.html
mBluetoothLeService.close();
final boolean result = mBluetoothLeService.connect(mDeviceAddress);
connect_string = data_disconnect.get(position).getName();
Log.d(TAG, "Connect request result=" + result);
} else if (data_disconnect.get(position).getName().equals("HC-06")) {
msg.setText("连接蓝牙中");
progressDialog.show();
BluetoothDevice device = mBluetoothAdapter
.getRemoteDevice(data_disconnect.get(position).getAddress());
// Attempt to connect to the device
connect(device);
connect_string = data_disconnect.get(position).getName();
datahc06_onitemclick =
Toast.makeText(getApplicationContext(), "该功能只支持连接HC-06,08蓝牙模块", Toast.LENGTH_SHORT).show();
//判断com.hf.tabhost.BluetoothLeService是否被系统杀死
public static boolean isServiceRunning(Context mContext, String className) {
boolean isRunning =
ActivityManager activityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
List&ActivityManager.RunningServiceInfo& serviceList = activityManager.getRunningServices(30);
if (!(serviceList.size() & 0)) {
for (int i = 0; i & serviceList.size(); i++) {
if (serviceList.get(i).service.getClassName().equals(className) == true) {
isRunning =
return isR
protected void onDestroy() {
super.onDestroy();
// Make sure we're not doing discovery anymore
if (mBluetoothAdapter != null) {
mBluetoothAdapter.cancelDiscovery();
// Unregister broadcast listeners
this.unregisterReceiver(mReceiver);
// 解除广播接收器
unregisterReceiver(mGattUpdateReceiver);
mBluetoothLeService =
5.代码下载地址:CSDN:
CSDN上传下载分不能为0了所以我选择了最少的2分,资源分不多的可以去我github下载,喜欢的可以点个star哦,谢谢了!
github下载地址:
6.还有一个楼主写了一个专门用于arduino控制蓝牙小车的APP喜欢的和需要的可以去应用宝下载下来爽爽哦,个人感觉比SPP功能强太多哦,欢迎下载,搜索HFEasyControl!
6.插播几张APP的截图给大家爽爽

我要回帖

更多关于 android 蓝牙2.0 的文章

 

随机推荐