android 连接蓝牙打印机 BluetoothAdapter
  
源码下载地址:https://github.com/yylxy/BluetoothText.git


public class PrintActivity extends AppCompatActivity {
//设备列表
private ListView listView;
    private ArrayList<PrintBean> 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<PrintBean> 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<PrintBean> 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的更多相关文章

  1. H5开发 连接蓝牙打印机 打印标签(斑马ZR628)

    1.连接蓝牙打印机(先用手机自带蓝牙进行配对),然后绑定出已配对的蓝牙设备(用来选择/切换打印机之用),代码如下 已配对蓝牙设备,中显示的就是已连接的,点击一下即可 代码: <!DOCTYPE ...

  2. Android调用蓝牙打印机

    首先需要一个jar包,bluesdk,请自行百度. 具体排版样式跟网络打印机打印排版样式实现一样,这里不多叙述,只贴一个实现方法代码.蓝牙打印机使用前需要先跟手机配对,可以保存在本地,记录下地址,这里 ...

  3. android 连接蓝牙扫码枪,程序崩溃之onConfigurationChanged

    当android手机通过蓝牙连接扫码枪时,程序崩溃的原因之一是:键盘弹出或隐藏,触发程序走了onDestory->onCreate的生命周期,从而可能使得页面的某些初始化数据被清除了. 解决方法 ...

  4. Android 连接蓝牙扫码器 无输入框

    Android 的APP 需要集成一个蓝牙扫码器, 特别的是,需要扫码的地方是没有输入框的(EditText),不能通过直觉上理解的通过对EditText输入事件进行监听处理,取得扫码结果.并且设备也 ...

  5. android蓝牙打印机

    您还未登录!|登录|注册|帮助 首页 业界 移动 云计算 研发 论坛 博客 下载 更多 reality_jie的专栏 编程的过程是一种微妙的享受       目录视图 摘要视图 订阅 CSDN2013 ...

  6. ubuntu16.04连接android手机蓝牙共享网络热点

    最近的想要用android手机蓝牙共享wifi网络给ubuntu16.04系统用,查了好多资料,发现网上很少有有用的.自己实践后分享如下. 第一步:手机与电脑配对:         该步骤比较简单,网 ...

  7. 蓝牙学习笔记二(Android连接问题)

    可以通过以下两点加速蓝牙连接: 1.更新连接参数 interval:连接间隔(connection intervals ),范围在 7.5 毫秒 到 4 秒. latency:连接延迟 ... 还有一 ...

  8. 微信小程序蓝牙连接小票打印机

    1.连接蓝牙 (第一次发表博客)   第一步打开蓝牙并搜索附近打印机设备// startSearch: function() { var that = this wx.openBluetoothAda ...

  9. Android实现蓝牙远程连接遇到的问题

    主要问到的问题:1.uuid获取不到,一直为空,后来发现android4.2之前使用uuid这种方法,目前尽量不使用uuid方式 2.socket.connect()出错,报read failed, ...

随机推荐

  1. thrift简单示例 (基于C++)

    这个thrift的简单示例, 来源于官网 (http://thrift.apache.org/tutorial/cpp), 因为我觉得官网的例子已经很简单了, 所以没有写新的示例, 关于安装的教程, ...

  2. H3C 802.11 WEP加密原理

  3. golang版本管理工具GO111MODULE

    在go1.11版本前,想要对go语言包进行管理,只能依赖第三方库实现,比如Vendor,GoVendor,GoDep,Dep,Glide等等. 1. 开启GO111MODULE 用环境变量 GO111 ...

  4. 安装nginx环境(含lua)时遇到报错ngx_http_lua_common.h:20:20: error: luajit.h: No such file or directory的解决

    下面是安装nginx+lua环境时使用的相关模块及版本,ngx_devel_kit和lua-nginx-module模块用的都是github上最新的模块.并进行了LuaJIT的安装. #Install ...

  5. 《BUG创造队》第六次作业:团队项目系统设计改进与详细设计

    项目 内容 这个作业属于哪个课程 2016级软件工程 这个作业的要求在哪里 实验十 团队作业6:团队项目系统设计改进与详细设计 团队名称 BUG创造队 作业学习目标 1.编写完整<软件系统设计说 ...

  6. 开发Electron可能用到的工具

    nodejs:搭载谷歌v8内核的高性能的node环境npm:包管理工具webpack:模块打包器jQuery:js必备库Bootstrap:css必备库react:用于构建用户界面的库vue:构建数据 ...

  7. java代码实现文件的下载功能

    昨天,根据需求文档的要求,自己要做一个关于文件下载的功能,从学校毕业已经很久了,自己好长时间都没有做过这个了,于是自己上网百度,最终开发出来的代码如下: 哦!对了,我先说一下我的思路,首先需要获取服务 ...

  8. IGC(Interleaved Group Convolutions)

    深度学习被引起关注是在2012年,用神经网络训练的一个分类模型在ImagNet上取得了第一名,而且其分类精度比第二名高出10多个点,当时所使用的模型为AlexNet,现在看来其为一个比较简单的网络,而 ...

  9. robot framework中如何为每个测试用例,测试集准备数据或销毁数据

    Suite Setup:在这个测试集的所有测试用例开始测试之前运行(类似于junit的@BeforeClass) Suite Teardown:在这个测试集的所有测试用例结束之后运行(类似于junit ...

  10. LeetCode 1004. Max Consecutive Ones III

    原题链接在这里:https://leetcode.com/problems/max-consecutive-ones-iii/ 题目: Given an array A of 0s and 1s, w ...