package com.lingrui.btprint; import android.Manifest; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import androidx.activity.EdgeToEdge; import androidx.activity.result.ActivityResult; import androidx.activity.result.ActivityResultCallback; import androidx.activity.result.ActivityResultLauncher; import androidx.activity.result.contract.ActivityResultContracts; import androidx.annotation.RequiresApi; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.Method; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Set; import java.util.UUID; public class MainActivity extends AppCompatActivity implements View.OnClickListener { // 弹窗 private Toast mToast; // 常量 private static final int REQ_PERMISSION_CODE = 1; // 蓝牙权限列表 public ArrayList<String> requestList = new ArrayList<>(); // 搜索蓝牙广播 private IntentFilter foundFilter; // public ArrayAdapter adapter1; //定义一个列表,存蓝牙设备的地址。 public ArrayList<String> arrayList = new ArrayList<>(); //定义一个列表,存蓝牙设备地址,用于显示。 public ArrayList<String> deviceName = new ArrayList<>(); private BluetoothSocket btSocket; private String TAG = ""; public static final int RECV_VIEW = 0; public static final int NOTICE_VIEW = 1; private static OutputStream outputStream = null; private static InputStream inputStream = null; public static String MY_UUID = "DC:0D:30:D6:0F:50"; /** * 代表本地蓝牙适配器(蓝牙无线电)。BluetoothAdapter是所有蓝牙交互的入口。 * 使用这个你可以发现其他蓝牙设备,查询已配对的设备列表, * 使用一个已知的MAC地址来实例化一个BluetoothDevice, * 以及创建一个BluetoothServerSocket来为监听与其他设备的通信。 */ private BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); /** * 代表一个远程蓝牙设备,使用这个来请求一个与远程设备的BluetoothSocket连接, * 或者查询关于设备名称、地址、类和连接状态等设备信息。 */ private BluetoothDevice mBluetoothDevice = null; /** * 代表一个蓝牙socket的接口(和TCP Socket类似)。这是一个连接点, * 它允许一个应用与其他蓝牙设备通过InputStream和OutputStream交换数据。 */ private BluetoothSocket mBluetoothSocket = null; private String pdfPath=""; //替换旧版本中的startactivityresult public ActivityResultLauncher<Intent> register; ActivityResultLauncher<Intent> startBlueTooth = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() { @Override public void onActivityResult(ActivityResult result) { if (result == null) { Log.e("error:", "打开失败"); } else { if (result.getResultCode() == RESULT_CANCELED) { Log.d("debug", "用户取消"); } } } }); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); EdgeToEdge.enable(this); setContentView(R.layout.activity_main); //点击蓝牙按钮 Button btBlt = findViewById(R.id.bt_blt); btBlt.setOnClickListener(this); // 通过id获取“是否支持蓝牙”按钮 Button button_3 = (Button) findViewById(R.id.button3); // 是否支持蓝牙按钮点击事件处理函数 button_3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // 获取蓝牙权限 getPermision(); // 判断是否支持蓝牙 boolean ret = isSupportBlueTooth(); // 弹窗显示结果 showToast("是否支持蓝牙" + ret); } }); //当前蓝牙状态 Button button_4 = findViewById(R.id.button4); button_4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //获取蓝牙权限 getPermision(); //显示蓝牙状态; boolean ret = getBlueToothStatus(); showToast("当前蓝牙状态:" + ret); } }); //打开蓝牙按钮点击事件 Button bt_open = findViewById(R.id.button7); bt_open.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { boolean ret = turnOnBlueTooth(MainActivity.this, 1); showToast("蓝牙开启状态:" + ret); } }); //关闭蓝牙点击事件 Button bt_close = findViewById(R.id.button8); bt_close.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { turnOffBlueTooth(); } }); //打印 Button bt_print = findViewById(R.id.bt_print); bt_print.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { Log.d("debug", "蓝牙打印按钮0"); if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) { return; } MY_UUID = "00001101-0000-1000-8000-00805F9B34FB"; Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices(); //getBondedDevices 方法返回已经配对的蓝牙设备的集合。通过遍历集合,可以获取设备的名称和地址等信息 //或者,根据已绑定的名称和网卡信息,强制指定; for (BluetoothDevice device : pairedDevices) { String deviceName = device.getName(); String deviceAddress = device.getAddress(); // 处理找到的设备信息,这是最后一个绑定的设备,如果有多个绑定的打印机,应该做一个选择的界面,让人手工点击,或选择默认的 mBluetoothDevice = device; } BluetoothSocket socket = mBluetoothDevice.createRfcommSocketToServiceRecord(UUID.fromString(MY_UUID)); Log.d("debug", MY_UUID); socket.connect(); // 开启一个子线程 new Thread() { public void run() { try { //调用另一个Pos 打印类 Pos pos = new Pos(socket,"GBK"); //初始化打印机 pos.initPos(); pos.bold(true); pos.printTabSpace(2); pos.printWordSpace(1); pos.printText("**测试店铺"); pos.printLocation(0); pos.printTextNewLine("----------------------------------------------"); pos.bold(false); pos.printTextNewLine("订 单 号:1005199"); pos.printTextNewLine("用 户 名:15712937281"); pos.printTextNewLine("桌 号:3号桌"); pos.printTextNewLine("订单状态:订单已确认"); pos.printTextNewLine("订单日期:2016/2/19 12:34:53"); pos.printTextNewLine("付 款 人:线下支付(服务员:宝哥)"); pos.printTextNewLine("服 务 员:1001"); pos.printTextNewLine("订单备注:不要辣,少盐"); pos.printLine(2); pos.printText("品项"); pos.printLocation(20, 1); pos.printText("单价"); pos.printLocation(99, 1); pos.printWordSpace(1); pos.printText("数量"); pos.printWordSpace(3); pos.printText("小计"); pos.printTextNewLine("----------------------------------------------"); pos.printLocation(1); pos.printLine(2); //打印二维码 pos.qrCode("http://blog.csdn.net/haovip123"); //切纸 pos.feedAndCut(); pos.closeIOAndSocket(); pos = null; } catch (UnknownHostException e) { showToast("错误1:"+e.getMessage()); e.printStackTrace(); } catch (IOException e) { showToast("错误2:"+e.getMessage()); e.printStackTrace(); } } }.start(); /* //连接成功后,我们可以通过蓝牙连接发送打印指令给蓝牙标签打印机。 outputStream = socket.getOutputStream(); StringBuilder content = new StringBuilder(); //设置纸张大小,浓度等打印机参数 byte[] sizeCmd = {0x1D, 0x57, 0x40, 0x1D, 0x57, 0x40}; outputStream.write(sizeCmd); byte[] densityCmd = {0x1D, 0x63, 0x30}; outputStream.write(densityCmd); //检查打印机状态的代码示例 inputStream = socket.getInputStream(); byte[] statusCmd = {0x10, 0x04, 0x01}; outputStream.write(statusCmd); outputStream.flush(); int tmp = inputStream.read(); if (tmp == 18) { showToast("读取打印机状态成功"); ; } else { showToast("读取打印机状态失败"+String.valueOf(tmp)); //return ; } int bytesRead; String ptString="壮骨麝香止痛膏\n";*/ //outputStream.write(content.toString().getBytes("GBK")); } catch (Exception ex) { showToast("打印出错:"+ex.getMessage()); } } }); //打印PDF 测试 Button bt_pdf = findViewById(R.id.bt_pdf); bt_pdf.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { File pdf; if (TextUtils.isEmpty(pdfPath)) { return; } pdf = new File(pdfPath); if (!pdf.exists()) { return; } } }); //使蓝牙可见点击事件 Button bt_visable = findViewById(R.id.button9); bt_visable.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { enableVisibly(MainActivity.this); } }); // 通过id获取”搜索可见蓝牙“按钮 Button button_6 = (Button) findViewById(R.id.button10); // 绑定按钮点击事件处理函数 button_6.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // 获取蓝牙权限 getPermision(); // 注册广播 registerReceiver(bluetoothReceiver, foundFilter); // 初始化各列表 arrayList.clear(); deviceName.clear(); adapter1.notifyDataSetChanged(); // 开始搜索 findDevice(); } }); //搜索蓝牙的广播 foundFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND); foundFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED); foundFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); // 获取ListView组件 ListView listView = (ListView) findViewById(R.id.listview1); // 实例化ArrayAdapter对象 adapter1 = new ArrayAdapter(this, android.R.layout.simple_expandable_list_item_1, deviceName); // 添加到ListView组件中 listView.setAdapter(adapter1); // 通过id获取”查看已绑定蓝牙“按钮 Button button_7 = (Button) findViewById(R.id.button11); // 绑定按钮点击事件处理函数 button_7.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // 获取蓝牙权限 getPermision(); // 初始化各列表 deviceName.clear(); arrayList.clear(); adapter1.notifyDataSetChanged(); // 获取已绑定蓝牙 ArrayList<BluetoothDevice> bluetoothDevices = getBondedDeviceList(); // 更新列表 for (int i = 0; i < bluetoothDevices.size(); i++) { BluetoothDevice device = bluetoothDevices.get(i); arrayList.add(device.getAddress()); if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) { return; } if (device.getBondState() == 12) { deviceName.add("设备名:" + device.getName() + "\n" + "设备地址:" + device.getAddress() + "\n" + "连接状态:已配对" + "\n"); } else if (device.getBondState() == 10) { deviceName.add("设备名:" + device.getName() + "\n" + "设备地址:" + device.getAddress() + "\n" + "连接状态:未配对" + "\n"); } else { deviceName.add("设备名:" + device.getName() + "\n" + "设备地址:" + device.getAddress() + "\n" + "连接状态:未知" + "\n"); } adapter1.notifyDataSetChanged(); } } }); //列表框监听事件 listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { CharSequence content = ((TextView) view).getText(); String con = content.toString(); String[] conArray = con.split("\n"); String rightStr = conArray[1].substring(5, conArray[1].length()); BluetoothDevice device = find_device(rightStr); if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return; } if (device.getBondState() == 10) { mBluetoothAdapter.cancelDiscovery(); ; String s = "设备名:" + device.getName() + "\n" + "设备地址:" + device.getAddress() + "\n" + "连接状态:未配对" + "\n"; deviceName.remove(s); device.createBond(); s = "设备名:" + device.getName() + "\n" + "设备地址:" + device.getAddress() + "\n" + "连接状态:已配对" + "\n"; deviceName.add(s); adapter1.notifyDataSetChanged(); showToast("配对:" + device.getName()); } else { mBluetoothAdapter.cancelDiscovery(); ; String s2 = "设备名:" + device.getName() + "\n" + "设备地址:" + device.getAddress() + "\n" + "连接状态:已配对" + "\n"; if (deviceName.contains(s2)) { unpairDevice(device); deviceName.remove(s2); s2 = "设备名:" + device.getName() + "\n" + "设备地址:" + device.getAddress() + "\n" + "连接状态:未配对" + "\n"; deviceName.add(s2); adapter1.notifyDataSetChanged(); showToast("取消配对:" + device.getName()); } } } }); } /** * 是否支持蓝牙 * @return true支持,false不支持 */ public boolean isSupportBlueTooth() { // 若支持蓝牙,则本地适配器不为null if (mBluetoothAdapter != null) { return true; } // 否则不支持 else { return false; } } /** * 判断当前蓝牙状态 * @return true为打开,false为关闭 */ public boolean getBlueToothStatus() { // 断言?为了避免mAdapter为null导致return出错 assert (mBluetoothAdapter != null); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return false; } boolean disable = mBluetoothAdapter.disable(); showToast("tttt:" + disable); boolean ret = mBluetoothAdapter.isEnabled(); showToast("tttt:" + ret); return ret; } /** * 打开蓝牙 */ public boolean turnOnBlueTooth(Activity activity, int requestCode) { //检查蓝牙权限 getPermision(); if (!mBluetoothAdapter.isEnabled()) { Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); register.launch(intent); Log.d("debug", "启动蓝牙"); //activity.startActivityForResult(intent, requestCode); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return false; } boolean enable = mBluetoothAdapter.enable(); Log.d("debug", "蓝牙开启状态:" + String.valueOf(enable)); return true; } else { return true; } } /** * 关闭蓝牙 * @return */ public void turnOffBlueTooth() { if (mBluetoothAdapter.isEnabled()) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { checkConnectPermission(); } boolean ret = mBluetoothAdapter.disable(); showToast("蓝牙关闭:" + ret); } } @Override public void onClick(View v) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { checkConnectPermission(); } Toast.makeText(getApplicationContext(), "蓝牙TEST", Toast.LENGTH_SHORT).show(); try { Log.d("debug", "点击打开蓝牙按钮"); mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); // 如果设备不支持蓝牙 if (mBluetoothAdapter == null) { Log.d("debug", "设备不支持蓝牙"); return; } // 设备支持蓝牙功能,启动蓝牙 if (!mBluetoothAdapter.isEnabled()) { register.launch(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)); Log.d("debug", "启动蓝牙"); } //打开蓝牙 if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) { return; } boolean enable = mBluetoothAdapter.enable(); Log.d("debug", "蓝牙开启状态:" + String.valueOf(enable)); //取得蓝牙开启状态 //一旦蓝牙已经打开,我们可以使用蓝牙适配器来搜索附近的蓝牙设备 if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) { return; } Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices(); //getBondedDevices 方法返回已经配对的蓝牙设备的集合。通过遍历集合,可以获取设备的名称和地址等信息 for (BluetoothDevice device : pairedDevices) { String deviceName = device.getName(); String deviceAddress = device.getAddress(); // 处理找到的设备信息 mBluetoothDevice = device; } Log.d("debug", "步骤四:连接蓝牙设备"); Toast.makeText(getApplicationContext(), "蓝牙TEST", Toast.LENGTH_SHORT).show(); /*步骤四:连接蓝牙设备 在搜索到蓝牙设备后,我们需要选择一个设备进行连接*/ MY_UUID = "00001101-0000-1000-8000-00805F9B34FB"; BluetoothSocket socket = mBluetoothDevice.createRfcommSocketToServiceRecord(UUID.fromString(MY_UUID)); Log.d("debug", MY_UUID); socket.connect(); //连接成功后,我们可以通过蓝牙连接发送打印指令给蓝牙标签打印机。 OutputStream outputStream = socket.getOutputStream(); String ptString="壮骨麝香止痛膏\n"; ptString +="壮骨麝香止痛膏\n"; ptString +="壮骨麝香止痛膏\n"; ptString +="壮骨麝香止痛膏\n"; printPDF("88.pdf") ; //outputStream.write(ptString.getBytes("GBK")); PrintUtils.setOutputStream(outputStream); testPrint(); byte[] bytes = {29, 86, 0}; outputStream.write(bytes); socket.close();; } catch (IllegalStateException | IOException e) { Log.d("debug", e.getMessage()); Toast.makeText(getApplicationContext(), "蓝牙打开失败:" + "\n" + e.getMessage(), Toast.LENGTH_SHORT).show(); } } @RequiresApi(api = Build.VERSION_CODES.S) private void checkConnectPermission() { if (ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_DENIED) { Log.i("MES", "SUCCESS"); ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.BLUETOOTH_CONNECT}, 2); } if (ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_DENIED) { Log.i("MES", "SUCCESS"); ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 2); } if (ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.BLUETOOTH_SCAN) == PackageManager.PERMISSION_DENIED) { Log.i("MES", "SUCCESS"); ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.BLUETOOTH_SCAN}, 2); } } /** * 动态申请权限 */ public void getPermision() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { requestList.add(Manifest.permission.BLUETOOTH_SCAN); requestList.add(Manifest.permission.BLUETOOTH_ADVERTISE); requestList.add(Manifest.permission.BLUETOOTH_CONNECT); requestList.add(Manifest.permission.ACCESS_FINE_LOCATION); requestList.add(Manifest.permission.ACCESS_COARSE_LOCATION); requestList.add(Manifest.permission.BLUETOOTH); } if (requestList.size() != 0) { ActivityCompat.requestPermissions(this, requestList.toArray(new String[0]), REQ_PERMISSION_CODE); } } /** * 打开蓝牙可见性 * @param context */ public void enableVisibly(Context context) { getPermision(); Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_ADVERTISE) != PackageManager.PERMISSION_GRANTED) { return; } context.startActivity(discoverableIntent); //Context.register.launch(discoverableIntent); } /** * Toast弹窗显示 * @param text 显示文本 */ public void showToast(String text) { // 若Toast控件未初始化 if (mToast == null) { // 则初始化 mToast = Toast.makeText(this, text, Toast.LENGTH_SHORT); } // 否则 else { // 修改显示文本 mToast.setText(text); } // 显示 mToast.show(); } // 蓝牙状态改变广播 private BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1); switch (state) { case BluetoothAdapter.STATE_OFF: showToast("STATE_OFF"); break; case BluetoothAdapter.STATE_ON: showToast("STATE_ON"); break; case BluetoothAdapter.STATE_TURNING_OFF: showToast("STATE_TURNING_OFF"); break; case BluetoothAdapter.STATE_TURNING_ON: showToast("STATE_TURNING_ON"); break; default: showToast("UnKnow STATE"); unregisterReceiver(this); break; } } }; private final BroadcastReceiver bluetoothReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (BluetoothDevice.ACTION_FOUND.equals(action)) { String s; BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) { return; } if (device.getBondState() == 12) { s = "设备名:" + device.getName() + "\n" + "设备地址:" + device.getAddress() + "\n" + "连接状态:已配对" + "\n"; } else if (device.getBondState() == 10) { s = "设备名:" + device.getName() + "\n" + "设备地址:" + device.getAddress() + "\n" + "连接状态:未配对" + "\n"; } else { s = "设备名:" + device.getName() + "\n" + "设备地址:" + device.getAddress() + "\n" + "连接状态:未知" + "\n"; } if (!deviceName.contains(s)) { deviceName.add(s);//将搜索到的蓝牙名称和地址添加到列表。 arrayList.add(device.getAddress());//将搜索到的蓝牙地址添加到列表。 adapter1.notifyDataSetChanged();//更新 } } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { showToast("搜索结束"); unregisterReceiver(this); } else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) { showToast("开始搜索"); } } }; /** * 获取绑定设备 * @return */ public ArrayList<BluetoothDevice> getBondedDeviceList() { getPermision(); return new ArrayList<BluetoothDevice>(mBluetoothAdapter.getBondedDevices()); } /** * 查找设备 */ public boolean findDevice() { assert (mBluetoothAdapter != null); if (mBluetoothAdapter.isDiscovering()) { mBluetoothAdapter.cancelDiscovery(); return false; } else { return mBluetoothAdapter.startDiscovery(); } } /** * 根据蓝牙地址找到相应的设备 * @param addr * @return */ public BluetoothDevice find_device(String addr) { return mBluetoothAdapter.getRemoteDevice(addr); } /** * 连接设备 */ public void connect_init(BluetoothDevice device) { mBluetoothAdapter.cancelDiscovery(); try { Log.d("Debug ","ttttttttttttttttttttt"); Method clientMethod = device.getClass().getMethod("createRfcommSocketToServiceRecord", new Class[]{int.class}); btSocket = (BluetoothSocket) clientMethod.invoke(device, 1); connect(btSocket); } catch (Exception e) { e.printStackTrace(); } } public void connect(final BluetoothSocket btSocket) { try { if (btSocket.isConnected()) { Log.e(TAG, "connect: 已经连接"); return; } if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return; } btSocket.connect(); if (btSocket.isConnected()){ Log.e(TAG, "connect: 连接成功"); }else{ Log.e(TAG, "connect: 连接失败"); btSocket.close(); } }catch (Exception e){e.printStackTrace();} } /** * 设置打印格式 * * @param command 格式指令 */ public static void selectCommand(byte[] command) { try { outputStream.write(command); outputStream.flush(); } catch (IOException e) { e.printStackTrace(); } } /** * 尝试取消配对 * @param device */ private void unpairDevice(BluetoothDevice device) { try { Method m = device.getClass() .getMethod("removeBond", (Class[]) null); m.invoke(device, (Object[]) null); } catch (Exception e) { e.printStackTrace(); } } void testPrint(){ showToast("测试打印PrintUtils"); PrintUtils.setOutputStream(outputStream); showToast("测试打印PrintUtils111111111111"); PrintUtils.selectCommand(PrintUtils.RESET); showToast("测试打印PrintUtils22222222222222"); PrintUtils.selectCommand(PrintUtils.LINE_SPACING_DEFAULT); showToast("测试打印PrintUtils333333333333"); PrintUtils.selectCommand(PrintUtils.ALIGN_CENTER); PrintUtils.printText("美食餐厅\n\n"); PrintUtils.selectCommand(PrintUtils.DOUBLE_HEIGHT_WIDTH); PrintUtils.printText("桌号:1号桌\n\n"); PrintUtils.selectCommand(PrintUtils.NORMAL); PrintUtils.selectCommand(PrintUtils.ALIGN_LEFT); PrintUtils.printText(PrintUtils.printTwoData("订单编号", "201507161515\n")); PrintUtils.printText(PrintUtils.printTwoData("点菜时间", "2016-02-16 10:46\n")); PrintUtils.printText(PrintUtils.printTwoData("上菜时间", "2016-02-16 11:46\n")); PrintUtils.printText(PrintUtils.printTwoData("人数:2人", "收银员:张三\n")); PrintUtils.printText("--------------------------------\n"); PrintUtils.selectCommand(PrintUtils.BOLD); PrintUtils.printText(PrintUtils.printThreeData("项目", "数量", "金额\n")); PrintUtils.printText("--------------------------------\n"); PrintUtils.selectCommand(PrintUtils.BOLD_CANCEL); PrintUtils.printText(PrintUtils.printThreeData("面", "1", "0.00\n")); PrintUtils.printText(PrintUtils.printThreeData("米饭", "1", "6.00\n")); PrintUtils.printText(PrintUtils.printThreeData("铁板烧", "1", "26.00\n")); PrintUtils.printText(PrintUtils.printThreeData("一个测试", "1", "226.00\n")); PrintUtils.printText(PrintUtils.printThreeData("牛肉面啊啊", "1", "2226.00\n")); PrintUtils.printText(PrintUtils.printThreeData("牛肉面啊啊啊牛肉面啊啊啊", "888", "98886.00\n")); PrintUtils.printText("--------------------------------\n"); PrintUtils.printText(PrintUtils.printTwoData("合计", "53.50\n")); PrintUtils.printText(PrintUtils.printTwoData("抹零", "3.50\n")); PrintUtils.printText("--------------------------------\n"); PrintUtils.printText(PrintUtils.printTwoData("应收", "50.00\n")); PrintUtils.printText("--------------------------------\n"); PrintUtils.selectCommand(PrintUtils.ALIGN_LEFT); PrintUtils.printText("备注:不要辣、不要香菜"); PrintUtils.printText("\n\n\n\n\n"); } /** * @param pdfPath 全路径 */ public void printPDF(final String pdfPath) { File pdf; if (TextUtils.isEmpty(pdfPath)) { return; } pdf = new File(pdfPath); if (!pdf.exists()) { return; } byte[] buf = new byte[1024]; int bytesRead; FileInputStream input=null; try { input = new FileInputStream(pdfPath); while ((bytesRead = input.read(buf)) > 0) { outputStream.write(buf, 0, bytesRead); } outputStream.flush(); } catch (IOException e) { Log.e("cmo", "打印图片异常:" + e.getMessage()); }try { input.close(); } catch (IOException e) { e.printStackTrace(); } } }
标签:示例,PrintUtils,蓝牙,MainActivity,new,device,import,public From: https://www.cnblogs.com/lrzy/p/18159634