Android(安卓)蓝牙学习笔记(一)
首先扯点别的:这是我自己看蓝牙方面的知识的笔记,要是大家想看蓝牙方面的知识,可以看看链接中的文章,我看了看,写的也是没谁了,完全是android官网的翻译加详解,非常完美!http://blog.csdn.net/small_lee/article/details/50800722
估计一篇文章也写不完,应该写两篇,先给大家上图
第一:这篇文章完成的任务
现在就按照图片按钮的顺序从头往下讲解。完整的代码在文章的末尾贴上。使用蓝牙方面的功能需要在Androidmanifest.xml文件中添加两个权限
<uses-permission android:name="android.permission.BLUETOOTH"/> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
1 打开蓝牙:在使用蓝牙之前,你首先要明确你的设备是否支持蓝牙功能,如果支持的话,你就可以打开蓝牙;
BluetoothAdapter bluetoothAdapter= BluetoothAdapter.getDefaultAdapter();if (bluetoothAdapter == null) { Toast.makeText(this, "你的手机不支持蓝牙功能", Toast.LENGTH_SHORT).show(); } else { //设备支持蓝牙,打开蓝牙 if (!bluetoothAdapter.isEnabled()) { Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableIntent, REQUEST_ENABLE_BT); }
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_ENABLE_BT) { if (resultCode == RESULT_OK) { Toast.makeText(this, "成功打开蓝牙", Toast.LENGTH_SHORT).show(); } else if (resultCode == RESULT_CANCELED) { Toast.makeText(this, "打开蓝牙失败", Toast.LENGTH_SHORT).show(); } } }
如果得到的mBluetoothAdapter 为空的话,就说明你的设备不支持蓝牙,如果不为空,就可以打开蓝牙。打开之前还要来一个判断蓝牙是否已经打开了。!bluetoothAdapter.isEnabled()如果没打开,就打开蓝牙。看点击打开蓝牙按钮后的效果图。点击以后在onActivityResult做一个toast如果成功,就弹出成功打开蓝牙,否则弹出失败
在弹出的对话框中点击允许,然后手机的状态栏上的蓝牙图标就出来了,成功打开。
2:查找已配对的设备:如果你的设备上的蓝牙曾经和别的设备上的蓝牙配对过,那么你可以查找到你曾经配对过的设备的设备名,MAC地址等信息
//查找已配对的蓝牙设备 if (bluetoothAdapter != null) { Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices(); // If there are paired devices if (pairedDevices.size() > 0) { // Loop through paired devices for (BluetoothDevice device : pairedDevices) { lists.add(device.getName() + ":" + device.getAddress()); } adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, lists); listView.setAdapter(adapter); } else { Toast.makeText(this, "没有配对的蓝牙设备", Toast.LENGTH_SHORT).show(); } }
如果找到就显示在listView中,如果没有找到,就弹出一个提示,看效果如图
可以看到我曾经配对过一个设备 Lenovo S820 MAC地址是50:3C:C4:14:45
3:搜索设备 只要简单的调用BluetoothAdapter 的startDiscovery()方法就可以开始搜索附近的蓝牙设备。搜索过程是一个异步的过程,调用方法以后会立即返回一个boolean值用来指示搜索是否已经启动了。你需要注册一个广播接收器来得到搜索到的设备的相关信息。在oncreate()方法中注册
// Register the BroadcastReceiver IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); registerReceiver(mReceiver, filter);
自定义广播接收器
// Create a BroadcastReceiver for ACTION_FOUND private final BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); // When discovery finds a device if (BluetoothDevice.ACTION_FOUND.equals(action)) { Toast.makeText(MainActivity.this, "发现设备", Toast.LENGTH_SHORT).show(); // Get the BluetoothDevice object from the Intent BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); // Add the name and address to an array adapter to show in a ListView lists.add(device.getName() + ":" + device.getAddress()); adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, lists); listView.setAdapter(adapter); } else { Toast.makeText(MainActivity.this, "没有发现设备", Toast.LENGTH_SHORT).show(); } } };
点击搜索设备后的效果图,我的另一部手机 LenovoS820必须打开蓝牙并设置可让其他设备检测到。
4关闭搜索,一行代码搞定
//关闭搜索功能 if (bluetoothAdapter != null && bluetoothAdapter.isEnabled()) { bluetoothAdapter.cancelDiscovery(); }
5 关闭蓝牙,一行代码搞定
if (bluetoothAdapter != null && bluetoothAdapter.isEnabled()) { bluetoothAdapter.disable(); }
点击关闭蓝牙以后,手机状态栏中的蓝牙小图标会消失
6,设置蓝牙可发现:如果你是主动发起连接其他设备,不用设置此项,如果你是被动的被远端的设备发现的话就必须设置此项。如果你的蓝牙并没有打开的话,设置蓝牙可发现的时候会自动打开蓝牙。
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, MY_DISCOVERABLE_TIME);//第二个参数是自定义的可检测的时间我定义的是1024秒,(如果超出此时间,则手机蓝牙不可被发现) startActivityForResult(discoverableIntent, REQUEST_ENABLE_BT);
看图
当你点击允许的时候你的Activity中的onActivityResult()会收到一个回调,resultcode是你设置的蓝牙可检测的时间1024秒
if (requestCode == REQUEST_ENABLE_BT) { if (resultCode == MY_DISCOVERABLE_TIME) { Toast.makeText(this, "蓝牙设备可一被发现", Toast.LENGTH_SHORT).show(); Log.e("TAG", "蓝牙设备可被发现"); } }
看图
完整代码MainActivity.java activity_main.xml
package com.learnbluetooth;import android.bluetooth.BluetoothAdapter;import android.bluetooth.BluetoothDevice;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.content.IntentFilter;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.util.Log;import android.view.View;import android.widget.ArrayAdapter;import android.widget.Button;import android.widget.ListView;import android.widget.Toast;import java.util.ArrayList;import java.util.IllegalFormatCodePointException;import java.util.List;import java.util.Set;public class MainActivity extends AppCompatActivity implements View.OnClickListener { private static final int REQUEST_ENABLE_BT = 1; private static final int MY_DISCOVERABLE_TIME = 1024; Button button1, button2, button3, button4, button5, button6; ListView listView; ArrayAdapter<String> adapter; List<String> lists = new ArrayList<>(); BluetoothAdapter bluetoothAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button1 = (Button) findViewById(R.id.button1); button1.setOnClickListener(this); button2 = (Button) findViewById(R.id.button2); button2.setOnClickListener(this); button3 = (Button) findViewById(R.id.button3); button3.setOnClickListener(this); button4 = (Button) findViewById(R.id.button4); button4.setOnClickListener(this); button5 = (Button) findViewById(R.id.button5); button5.setOnClickListener(this); button6 = (Button) findViewById(R.id.button6); button6.setOnClickListener(this); listView = (ListView) findViewById(R.id.listView); bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); // Register the BroadcastReceiver IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); registerReceiver(mReceiver, filter); } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(mReceiver); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.button1: if (bluetoothAdapter == null) { Toast.makeText(this, "你的手机不支持蓝牙功能", Toast.LENGTH_SHORT).show(); } else { //设备支持蓝牙,打开蓝牙 if (!bluetoothAdapter.isEnabled()) { Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableIntent, REQUEST_ENABLE_BT); } } break; case R.id.button2: //查找已配对的蓝牙设备 if (bluetoothAdapter != null) { Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices(); // If there are paired devices if (pairedDevices.size() > 0) { // Loop through paired devices for (BluetoothDevice device : pairedDevices) { lists.add(device.getName() + ":" + device.getAddress()); } adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, lists); listView.setAdapter(adapter); } else { Toast.makeText(this, "没有配对的蓝牙设备", Toast.LENGTH_SHORT).show(); } } break; case R.id.button3: //搜索蓝牙 if (bluetoothAdapter != null && bluetoothAdapter.isEnabled()) { bluetoothAdapter.startDiscovery(); } Toast.makeText(this, "正在搜索", Toast.LENGTH_SHORT).show(); Log.e("TAG", "正在搜索"); break; case R.id.button4: //关闭搜索功能 if (bluetoothAdapter != null && bluetoothAdapter.isEnabled()) { bluetoothAdapter.cancelDiscovery(); } Toast.makeText(this, "关闭搜索", Toast.LENGTH_SHORT).show(); Log.e("TAG", "关闭搜索"); break; case R.id.button5: if (bluetoothAdapter != null && bluetoothAdapter.isEnabled()) { bluetoothAdapter.disable(); } break; case R.id.button6: Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, MY_DISCOVERABLE_TIME); startActivityForResult(discoverableIntent, REQUEST_ENABLE_BT); break; default: break; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_ENABLE_BT) { if (resultCode == RESULT_OK) { Toast.makeText(this, "成功打开蓝牙", Toast.LENGTH_SHORT).show(); } else if (resultCode == RESULT_CANCELED) { Toast.makeText(this, "打开蓝牙失败", Toast.LENGTH_SHORT).show(); }else if (resultCode == MY_DISCOVERABLE_TIME) { Toast.makeText(this, "蓝牙设备可被发现", Toast.LENGTH_SHORT).show(); Log.e("TAG", "蓝牙设备可被发现"); } } } // Create a BroadcastReceiver for ACTION_FOUND private final BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); // When discovery finds a device if (BluetoothDevice.ACTION_FOUND.equals(action)) { Toast.makeText(MainActivity.this, "发现设备", Toast.LENGTH_SHORT).show(); // Get the BluetoothDevice object from the Intent BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); // Add the name and address to an array adapter to show in a ListView lists.add(device.getName() + ":" + device.getAddress()); adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, lists); listView.setAdapter(adapter); } else { Toast.makeText(MainActivity.this, "没有发现设备", Toast.LENGTH_SHORT).show(); } } };}
<?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/button1" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="打开蓝牙" /> <Button android:id="@+id/button2" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="查找已配对的设备" /> <Button android:id="@+id/button3" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="搜索设备"/> <Button android:id="@+id/button4" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="停止搜索"/> <Button android:id="@+id/button5" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="关闭蓝牙"/> <Button android:id="@+id/button6" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="设置蓝牙可发现"/> <ListView android:id="@+id/listView" android:layout_width="match_parent" android:layout_height="wrap_content"></ListView></LinearLayout>
行,下篇继续,刚吃完饭,有点小困,去睡个觉先。唉,感觉自己时间很少,还想多玩玩,多休息休息,所以写的东西质量简直是垃圾。等以后自己时间多了,知识更完备,再认真写东西。我就是IT行业的诗人,文艺界的IT男。此时此刻,我想到了通哥。
更多相关文章
- Android(安卓)记录一次 代码重启设备的爬坑记录
- Android连接、断开蓝牙扫描枪时屏幕刷新
- androidmanifest.xml的一些高级属性
- 如何在android设备上insmod自己单独编译的.ko,解决签名问题
- Android中bluetooth的架构
- AndroidStudio中AVD虚拟机设备空间不足调试过程出现的黑屏问题及
- 钉钉开发Android调试微应用
- Android(蓝牙)
- AndroidADB工具使用