android 连接蓝牙打印机 BluetoothAdapter

源码下载地址:https://github.com/yylxy/BluetoothText.git

public class PrintActivity extends AppCompatActivity {

//设备列表

private ListView listView;

private ArrayList mBluetoothDevicesDatas;

private PrintAdapter adapter;

//蓝牙适配器

private BluetoothAdapter mBluetoothAdapter;

//请求的code

public static final int REQUEST_ENABLE_BT = 1;

private Switch mSwitch;

private FloatingActionButton mFloatingActionButton;

private ProgressBar mProgressBar;

private Toolbar toolbar;

private TextView searchHint;

/**

* 启动打印页面

*

* @param printContent 要打印的内容

*/

public static void starUi(Context context, String printContent) {

Intent intent = new Intent(context, PrintActivity.class);

intent.putExtra("id", id);

intent.putExtra("printContent", printContent);

context.startActivity(intent);

}

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

//广播注册

IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);

filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);

registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy

//初始化

mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

mSwitch = (Switch) findViewById(R.id.switch1);

mFloatingActionButton = (FloatingActionButton) findViewById(R.id.floatingActionButton);

mProgressBar = (ProgressBar) findViewById(R.id.progressBar3);

toolbar = (Toolbar) findViewById(R.id.toolbar);

searchHint = (TextView) findViewById(R.id.searchHint);

toolbar.setTitle("选择打印设备");

listView = (ListView) findViewById(R.id.listView);

mBluetoothDevicesDatas = new ArrayList<>();

String printContent=getIntent().getStringExtra("printContent");

adapter = new PrintAdapter(this, mBluetoothDevicesDatas, TextUtils.isEmpty(printContent)?"123456789完\n\n\n":printContent);

listView.setAdapter(adapter);

chechBluetooth();

addViewListener();

}

/**

* 判断有没有开启蓝牙

*/

private void chechBluetooth() {

//没有开启蓝牙

if (mBluetoothAdapter != null) {

if (!mBluetoothAdapter.isEnabled()) {

Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); // 设置蓝牙可见性,最多300秒

intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 20);

startActivityForResult(intent, REQUEST_ENABLE_BT);

setViewStatus(true);

//开启蓝牙

} else {

searchDevices();

setViewStatus(true);

mSwitch.setChecked(true);

}

}

}

/**

* 搜索状态调整

*

* @param isSearch 是否开始搜索

*/

private void setViewStatus(boolean isSearch) {

if (isSearch) {

mFloatingActionButton.setVisibility(View.GONE);

searchHint.setVisibility(View.VISIBLE);

mProgressBar.setVisibility(View.VISIBLE);

} else {

mFloatingActionButton.setVisibility(View.VISIBLE);

mProgressBar.setVisibility(View.GONE);

searchHint.setVisibility(View.GONE);

}

}

/**

* 添加View的监听

*/

private void addViewListener() {

//蓝牙的状态

mSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

@Override

public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

if (isChecked) {

openBluetooth();

setViewStatus(true);

} else {

closeBluetooth();

}

}

});

//重新搜索

mFloatingActionButton.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

if (mSwitch.isChecked()) {

searchDevices();

setViewStatus(true);

} else {

openBluetooth();

setViewStatus(true);

}

}

});

toolbar.setNavigationIcon(R.drawable.ic_arrow_back_black_24dp);

toolbar.setNavigationOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View view) {

Toast.makeText(PrintActivity.this, "88", Toast.LENGTH_SHORT).show();

}

});

}

@Override

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

super.onActivityResult(requestCode, resultCode, data);

if (resultCode == RESULT_OK && requestCode == REQUEST_ENABLE_BT) {

Log.e("text", "开启蓝牙");

searchDevices();

mSwitch.setChecked(true);

mBluetoothDevicesDatas.clear();

adapter.notifyDataSetChanged();

} else if (resultCode == RESULT_CANCELED && requestCode == REQUEST_ENABLE_BT) {

Log.e("text", "没有开启蓝牙");

mSwitch.setChecked(false);

setViewStatus(false);

}

}

/**

* 打开蓝牙

*/

public void openBluetooth() {

Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); // 设置蓝牙可见性,最多300秒

intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 20);

startActivityForResult(intent, REQUEST_ENABLE_BT);

}

/**

* 关闭蓝牙

*/

public void closeBluetooth() {

mBluetoothAdapter.disable();

}

/**

* 搜索蓝牙设备

*/

public void searchDevices() {

mBluetoothDevicesDatas.clear();

adapter.notifyDataSetChanged();

//开始搜索蓝牙设备

mBluetoothAdapter.startDiscovery();

}

/**

* 通过广播搜索蓝牙设备

*/

private final BroadcastReceiver mReceiver = new BroadcastReceiver() {

public void onReceive(Context context, Intent intent) {

String action = intent.getAction();

// 把搜索的设置添加到集合中

if (BluetoothDevice.ACTION_FOUND.equals(action)) {

BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

//已经匹配的设备

if (device.getBondState() == BluetoothDevice.BOND_BONDED) {

addBluetoothDevice(device);

//没有匹配的设备

} else {

addBluetoothDevice(device);

}

adapter.notifyDataSetChanged();

//搜索完成

} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {

setViewStatus(false);

}

}

/**

* 添加数据

* @param device 蓝牙设置对象

*/

private void addBluetoothDevice(BluetoothDevice device) {

for (int i = 0; i < mBluetoothDevicesDatas.size(); i ) {

if (device.getAddress().equals(mBluetoothDevicesDatas.get(i).getAddress())) {

mBluetoothDevicesDatas.remove(i);

}

}

if (device.getBondState() == BluetoothDevice.BOND_BONDED && device.getBluetoothClass().getDeviceClass() == PRINT_TYPE) {

mBluetoothDevicesDatas.add(0, new PrintBean(device));

} else {

mBluetoothDevicesDatas.add(new PrintBean(device));

}

}

};

}

class PrintAdapter extends BaseAdapter {

private ArrayList mBluetoothDevicesDatas;

private Context mContext;

//蓝牙适配器

private BluetoothAdapter mBluetoothAdapter;

//蓝牙socket对象

private BluetoothSocket mmSocket;

private UUID uuid;

//打印的输出流

private static OutputStream outputStream = null;

//搜索弹窗提示

ProgressDialog progressDialog = null;

private final int exceptionCod = 100;

//打印的内容

private String mPrintContent;

//在打印异常时更新ui

Handler handler = new Handler() {

@Override

public void handleMessage(Message msg) {

super.handleMessage(msg);

if (msg.what == exceptionCod) {

Toast.makeText(mContext, "打印发送失败,请稍后再试", Toast.LENGTH_SHORT).show();

if (progressDialog != null) {

progressDialog.dismiss();

}

}

}

};

/**

* @param context 上下文

* @param mBluetoothDevicesDatas 设备列表

* @param printContent 打印的内容

*/

public PrintAdapter(Context context, ArrayList mBluetoothDevicesDatas, String printContent) {

this.mBluetoothDevicesDatas = mBluetoothDevicesDatas;

mContext = context;

mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

mPrintContent = printContent;

uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

}

public int getCount() {

return mBluetoothDevicesDatas.size();

}

@Override

public Object getItem(int position) {

return position;

}

@Override

public long getItemId(int position) {

return position;

}

@Override

public View getView(final int position, View convertView, ViewGroup parent) {

convertView = LayoutInflater.from(mContext).inflate(R.layout.itme, null);

View icon = convertView.findViewById(R.id.icon);

TextView name = (TextView) convertView.findViewById(R.id.name);

TextView address = (TextView) convertView.findViewById(R.id.address);

TextView start = (TextView) convertView.findViewById(R.id.start);

final PrintBean dataBean = mBluetoothDevicesDatas.get(position);

icon.setBackgroundResource(dataBean.getTypeIcon());

name.setText(dataBean.name);

address.setText(dataBean.isConnect ? "已连接" : "未连接");

start.setText(dataBean.getDeviceType(start));

//点击连接与打印

convertView.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

try {

//如果已经连接并且是打印机

if (dataBean.isConnect && dataBean.getType() == PRINT_TYPE) {

if (mBluetoothAdapter.isEnabled()) {

new ConnectThread(mBluetoothAdapter.getRemoteDevice(dataBean.address)).start();

progressDialog = ProgressDialog.show(mContext, "提示", "正在打印...", true);

} else {

Toast.makeText(mContext, "蓝牙没有打开", Toast.LENGTH_SHORT).show();

}

//没有连接

} else {

//是打印机

if (dataBean.getType() == PRINT_TYPE) {

setConnect(mBluetoothAdapter.getRemoteDevice(dataBean.address), position);

//不是打印机

} else {

Toast.makeText(mContext, "该设备不是打印机", Toast.LENGTH_SHORT).show();

}

}

} catch (Exception e) {

e.printStackTrace();

}

}

});

return convertView;

}

/**

* 匹配设备

*

* @param device 设备

*/

private void setConnect(BluetoothDevice device, int position) {

try {

Method createBondMethod = BluetoothDevice.class.getMethod("createBond");

createBondMethod.invoke(device);

mBluetoothDevicesDatas.get(position).setConnect(true);

notifyDataSetChanged();

} catch (Exception e) {

e.printStackTrace();

}

}

/**

* 发送数据

*/

public void send(String sendData) {

try {

byte[] data = sendData.getBytes("gbk");

outputStream.write(data, 0, data.length);

outputStream.flush();

outputStream.close();

progressDialog.dismiss();

} catch (IOException e) {

e.printStackTrace();

handler.sendEmptyMessage(exceptionCod); // 向Handler发送消息,更新UI

}

}

/**

* 连接为客户端

*/

private class ConnectThread extends Thread {

public ConnectThread(BluetoothDevice device) {

try {

mmSocket = device.createRfcommSocketToServiceRecord(uuid);

} catch (IOException e) {

e.printStackTrace();

}

}

public void run() {

//取消的发现,因为它将减缓连接

mBluetoothAdapter.cancelDiscovery();

try {

//连接socket

mmSocket.connect();

//连接成功获取输出流

outputStream = mmSocket.getOutputStream();

send(mPrintContent);

} catch (Exception connectException) {

Log.e("test", "连接失败");

connectException.printStackTrace();

//异常时发消息更新UI

Message msg = new Message();

msg.what = exceptionCod;

// 向Handler发送消息,更新UI

handler.sendMessage(msg);

try {

mmSocket.close();

} catch (Exception closeException) {

closeException.printStackTrace();

}

return;

}

}

}

}

标签: android 连接蓝牙打印机 BluetoothAdapter

来源:https://www.icode9.com/content-4-387501.html

android 蓝牙地址连接打印机,android 连接蓝牙打印机 BluetoothAdapter相关推荐

  1. 蓝牙地址的name为null_蓝牙, enable协议栈流程

    文章开始之前,先看两张图 原谅我这个不擅长美工没有艺术细菌的程序媛,图画的很简陋,但也算是勾勒出了大致的流程如果你对这两张图感兴趣,那么欢迎继续阅读本文,也期待多多提出意见如果无感,甚至感觉目前根本没 ...

  2. android蓝牙配对 自动联接,Android系统下蓝牙自动配对连接方法

    Android系统下蓝牙自动配对连接方法 [专利摘要]本发明涉及一种Android系统下蓝牙自动配对连接方法,其包括如下步骤:步骤1.在Android设备端内存储上次进行蓝牙连接蓝牙外设的蓝牙地址,并 ...

  3. Android系统(168)---Android 开源项目分类汇总

    Android开源项目分类汇总 原网址:https://blog.csdn.net/prince77qiqiqq/article/details/51338330 Android 开源项目第一篇--个 ...

  4. 蓝牙Mesh学习总结一(蓝牙Mesh介绍)

    1.Mesh简介 Blutooth Low Energy Mesh 是基于低功耗蓝牙技术(BLE)的网状网络解决方案.目前使用的是泛洪网状网络(flooding-based mesh network) ...

  5. Android ble连接过程,Android开发之ble蓝牙

    前言 由于自己工作中需要开发ble的项目,于是在折腾了一段时间后也有所了解,便想写下来分享给大家,同时对自己的知识也是一种巩固 1.BLE介绍 BLE是Bluetooth Low Energy的缩写, ...

  6. Android蓝牙Ble基本操作-(连接2)

    前言: 连接采用nordicsemi库,其中nRF Connect也是使用该库. 蓝牙连接库.nordicsemi官网.nRF Connect apk使用教程.nRF Connect apk下载地址. ...

  7. Android蓝牙连接uuid,通过蓝牙UUID连接到android设备时遇到麻烦

    美好的一天,我试图创建一个蓝牙应用程序,但无法连接到另一个Android设备.似乎正在发生的问题是在传出连接createRfcommSocketToServiceRecord(UUID)中-我认为在这 ...

  8. Android Studio制作手机App:通过手机蓝牙(Bluetooth)与STM32上的低功耗蓝牙(HC-42)连接通信,实现手机端对单片机的控制。

    背景: 本文的内容是针对单片机蓝牙模块(HC-42)开发的手机App.在这之前,我想先声明一点,手机与手机间的蓝牙连接方式"与"手机与HC间的蓝牙连接方式"是不一样的.原 ...

  9. android 连接蓝牙音响,Android 扫描附近的蓝牙设备并连接蓝牙音响的示例

    Android 扫描附近的蓝牙设备并连接蓝牙音响的示例 发布时间:2020-09-10 04:30:39 来源:脚本之家 阅读:111 作者:叶应是叶 写了一个可以扫描附近蓝牙设备的小Demo,可以查 ...

最新文章

  1. 抗击新冠肺炎,如何进行实时动态时序图谱建模与分析?
  2. ACMNO.38 C语言-报数 有n人围成一圈,顺序排号。从第1个人开始报数(从1到3报数),凡报到3的人退出圈子,问最后留下的是原来的第几号的那位。
  3. Visual Studio 2005中web.sitemap 中扩展自定义属性的一些应用范例
  4. linux系统不关机添加硬盘吗,CentOS中不重启添加硬盘
  5. python电脑发音-Python如何实现文本转语音
  6. java 多线程下载文件并实时计算下载百分比(断点续传)
  7. MacBook Pro如何删除多余的专注模式
  8. python dlib人脸检测_Python 3 利用 Dlib 实现人脸检测和剪切
  9. Bootstrap固定导航条
  10. 2.js深入(以通俗易懂的语言解释JavaScript)
  11. 一篇总结得超全的前端进阶文章!入门、技巧、方法、书籍、网站...一步到位!
  12. 谷歌json插件_没用过这7款浏览器插件,你一定是假的程序员
  13. iphonex黑屏开不了机_iphonexr死机,iphonexr开不了机
  14. scopt解析参数实例
  15. Atitit.软件的建模种类and 建模语言选型and UML???
  16. 【在大学的快乐生活】锐捷校园网无感认证通过路由器mac地址克隆实现一账号多终端
  17. ECshop二次开发从开始
  18. 【python中级】 ico图标生成器
  19. 【车间调度】柔性作业车间调度问题的研究现状
  20. 适合普通人的基金投资研究工具之:且慢与基金组合

热门文章

  1. 高阶无穷小量和低阶无穷小量 洛必达的使用条件 三阶导数的几何意义  阶乘的意义,0的阶乘为什么等于1 泰勒公式简单理解,麦克劳林级数 带拉格朗日余项的泰勒公式和带皮亚诺余项的泰勒公式区别
  2. 2015年第4本(英文第3本):Godfather教父
  3. SQL Server 获取2019年节假日列表(可用于Java、.Net系统实现)
  4. [球体积交]Girlfriend 2021牛客多校第2场 F
  5. 【WSN定位】基于matlab灰狼算法优化无线传感器非测距定位【含Matlab源码 2008期】
  6. SageX3和车辆排队系统、地磅系统集成方案
  7. habor私有镜像仓库部署
  8. 一份超详细的UI设计规范全攻略
  9. 抖音小程序支付宝异步回调中验签php代码
  10. python输出字体的大小_Python之美——一只数据狗的笔记[长期更新]