首页 > 其他分享 >蓝牙实战(二)

蓝牙实战(二)

时间:2022-11-22 11:38:48浏览次数:39  
标签:实战 BluetoothDevice void BluetoothAdapter 蓝牙 private ACTION public


一.概述

这是蓝牙实战的第二篇,今天讲讲基本的操作,打开蓝牙可见性,查找设备,显示已绑定设备,先看效果图

蓝牙实战(二)_可见性

由于模拟器不支持蓝牙,所以没办法进行相应操作,大家下来可以到真机上测试一下,绝对没问题。

二.代码

1.BlueToothController

public class BlueToothController {

private BluetoothAdapter mAapter;

public BlueToothController() {
mAapter = BluetoothAdapter.getDefaultAdapter();
}
/**
* 打开蓝牙
* @param activity
* @param requestCode
*/
public void turnOnBlueTooth(Activity activity, int requestCode) {
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
activity.startActivityForResult(intent, requestCode);
// mAdapter.enable();
}
/**
* 打开蓝牙可见性
* @param context
*/
public void enableVisibly(Context context) {
Intent discoverableIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
context.startActivity(discoverableIntent);
}
/**
* 查找设备
*/
public void findDevice() {
assert (mAapter != null);
mAapter.startDiscovery();
}
/**
* 获取绑定设备
* @return
*/
public List<BluetoothDevice> getBondedDeviceList() {
return new ArrayList<>(mAapter.getBondedDevices());
}
}

2.DeviceAdapter

public class DeviceAdapter extends BaseAdapter {
private List<BluetoothDevice> mData;
private Context mContext;
public DeviceAdapter(List<BluetoothDevice> data, Context context) {
mData = data;
mContext = context.getApplicationContext();
}
@Override
public int getCount() {
return mData.size();
}
@Override
public Object getItem(int i) {
return mData.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
View itemView = view;
//复用View,优化性能
if( itemView == null) {
itemView = LayoutInflater.from(mContext).inflate(android.R.layout.simple_list_item_2,viewGroup,false);
}
TextView line1 = (TextView) itemView.findViewById(android.R.id.text1);
TextView line2 = (TextView) itemView.findViewById(android.R.id.text2);
//获取对应的蓝牙设备
BluetoothDevice device = (BluetoothDevice) getItem(i);
//显示名称
line1.setText(device.getName());
//显示地址
line2.setText(device.getAddress());

return itemView;
}
public void refresh(List<BluetoothDevice> data) {
mData = data;
notifyDataSetChanged();
}
}

3.MainActivity

public class MainActivity extends Activity {
public static final int REQUEST_CODE = 0;
private List<BluetoothDevice> mDeviceList = new ArrayList<>();
private List<BluetoothDevice> mBondedDeviceList = new ArrayList<>();
private BlueToothController mController = new BlueToothController();
private ListView mListView;
private DeviceAdapter mAdapter;
private Toast mToast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initActionBar();
setContentView(R.layout.activity_main);
initUI();
IntentFilter filter = new IntentFilter();
//开始查找
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
//结束查找
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
//查找设备
filter.addAction(BluetoothDevice.ACTION_FOUND);
//设备扫描模式改变
filter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
//绑定状态
filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
//注册广播
registerReceiver(mReceiver, filter);
//打开蓝牙
mController.turnOnBlueTooth(this, REQUEST_CODE);
}
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
//开始查找
if( BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action) ) {
setProgressBarIndeterminateVisibility(true);
//初始化数据列表
mDeviceList.clear();
mAdapter.notifyDataSetChanged();
}//查找结束
else if( BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
setProgressBarIndeterminateVisibility(false);
}//发现设备
else if( BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
//找到一个,添加一个
mDeviceList.add(device);
mAdapter.notifyDataSetChanged();
}
else if( BluetoothAdapter.ACTION_SCAN_MODE_CHANGED.equals(action)) {
int scanMode = intent.getIntExtra(BluetoothAdapter.EXTRA_SCAN_MODE,0);
if( scanMode == BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
setProgressBarIndeterminateVisibility(true);
}
else {
setProgressBarIndeterminateVisibility(false);
}
}
else if( BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action) ) {
BluetoothDevice remoteDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if( remoteDevice == null ) {
showToast("no device");
return;
}
int status = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE,0);
if( status == BluetoothDevice.BOND_BONDED) {
showToast("Bonded " + remoteDevice.getName());
}
else if( status == BluetoothDevice.BOND_BONDING){
showToast("Bonding " + remoteDevice.getName());
}
else if(status == BluetoothDevice.BOND_NONE){
showToast("Not bond " + remoteDevice.getName());
}
}
}
};
private void initUI() {
mListView = (ListView) findViewById(R.id.device_list);
mAdapter = new DeviceAdapter(mDeviceList, this);
mListView.setAdapter(mAdapter);
mListView.setOnItemClickListener(bindDeviceClick);
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mReceiver);
}
/**
* 创建菜单布局
* @param menu
* @return
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
private void showToast(String text) {
if( mToast == null) {
mToast = Toast.makeText(this, text, Toast.LENGTH_SHORT);
}
else {
mToast.setText(text);
}
mToast.show();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.enable_visiblity) {
mController.enableVisibly(this);
}
else if( id == R.id.find_device) {
//查找设备
mAdapter.refresh(mDeviceList);
mController.findDevice();
mListView.setOnItemClickListener(bindDeviceClick);
}
else if (id == R.id.bonded_device) {
//查看已绑定设备
mBondedDeviceList = mController.getBondedDeviceList();
mAdapter.refresh(mBondedDeviceList);
mListView.setOnItemClickListener(null);
}
return super.onOptionsItemSelected(item);
}
private AdapterView.OnItemClickListener bindDeviceClick = new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
BluetoothDevice device = mDeviceList.get(i);
device.createBond();//配对绑定
}
};
private void initActionBar() {
//在action的右边显示一个圆形进度条
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
//显示icon而不显示logo,因为有时候会定义两个图标
getActionBar().setDisplayUseLogoEnabled(false);
setProgressBarIndeterminate(true);
try {
ViewConfiguration config = ViewConfiguration.get(this);
Field menuKeyField = ViewConfiguration.class
.getDeclaredField("sHasPermanentMenuKey");
if (menuKeyField != null) {
menuKeyField.setAccessible(true);
menuKeyField.setBoolean(config, false);//设置为true,则菜单从底部弹出,并且右上角不显示overflow按钮,设置为false,
//则overflow按钮可见,并且从右上角显示按钮
}
} catch (Exception e) {
e.printStackTrace();
}
}
}


标签:实战,BluetoothDevice,void,BluetoothAdapter,蓝牙,private,ACTION,public
From: https://blog.51cto.com/u_10847930/5877240

相关文章

  • 蓝牙实战(一)
    一.概述在前面的三篇文章讲解蓝牙开发,写的比较详细,篇幅比较长,后面这几篇来点简单实用的,先看效果图二.代码代码如下:BlueToothController控制蓝牙操作publicclassBlueToot......
  • Android webview实战
    今天来使用webview进行一个实例演练,可以基本用到任何地方,目的在于熟悉一下webview的使用,基本算是入门的吧。先看一下效果图,接下来我们看看如何实现第一步:首先加载网页......
  • Golang学习日志 ━━ 理解依赖包的管理(mod/非mod)和加载方式(项目路径、相对路径、绝对
    go有很多种方法调用依赖包,mod又加入了对包的版本管理。方式太多不免有令人迷惑和混乱的地方,希望本文能帮助大家了解目前使用规则一、mod/非mod管理方式go提供了两种项目......
  • python flask实战订餐系统微信小程序-59flask部署单进程启动服务
    欢迎关注原创Python微信订餐小程序课程视频Python实战量化交易理财系统​​python​​​​flask​​实战订餐系统微信小程序-60nginx+uwsgi实现多进程访问​​​B站配套......
  • Note.js框架中的cluster集群和断言测试的实战剖析
    Cluster节点。Js在单个线程中运行单个实例。为了使用当前的多核系统,用户(开发人员)有时会使用一个Node字符串。js进程来处理加载任务。集群模块允许轻松创建共享服务器端口......
  • MySQL进阶实战2,那些年学过的事务
    一、MySQL服务器逻辑架构MySQL核心部分包括查询解析、分析、优化、缓存以及内置函数,所有跨存储引擎的功能,存储过程、触发器、视图等。存储引擎负责MySQL中数据的存储和提取......
  • 【2022-11-21】luffy项目实战(十二)
    一、支付宝支付介绍1.1入门"""1)支付宝API:六大接口https://docs.open.alipay.com/270/105900/2)支付宝工作流程(见下图):https://docs.open.alipay.com/270/105898/......
  • 无线实战视频
    service-port带外网管接口manageport带内网管接口ap管理接口与manage带内管理接口是同一个vlan同一个接口虚拟接口virtual接口,一般都配一个全局不可路由的地址1.1......
  • 深度学习之tensorflow2实战:多输出模型
    欢迎来到CNN实战,尽管我们刚刚开始,但还是要往前看!让我们开始吧! 数据集链接:https://pan.baidu.com/s/1zztS32iuNynepLq7jiF6RA提取码:ilxh,请下载好数据,在开始 导入......
  • 【Spring Cloud实战】Eurake服务注册与发现
    gitee地址:https://gitee.com/javaxiaobear/spring-cloud_study.git什么是服务治理?SpringCloud封装了Netflix公司开发的Eureka模块来实现服务治理。在传统的rpc远程调......