Я пытаюсь распечатать на bluetooth-принтере (DPP-350), но не могу добиться этого всю неделю.
Я прочитал много примеров, учебных пособий и всего, что нашел.Нет способа сделать это.
- Я могу подключиться к принтеру
- Я могу получить его имя и адрес (MAC)
Я знаю, что мой код не лучшим образом, но он должен работать.
Вот он:
public class MainActivity extends AppCompatActivity {
Button btnPrint;
TextView lblPrinterName;
ProgressBar progressBar;
String TAG = "BLUETOOTH ONLY";
BluetoothAdapter btAdapter;
BluetoothDevice btDevice;
private BluetoothSocket btSocket = null;
private OutputStream outputStream = null;
private InputStream inputStream = null;
Thread thread;
byte[] readBuffer;
int readBufferPosition;
volatile boolean stopWorker;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mine);
btnPrint = findViewById(R.id.btnPrint);
lblPrinterName = findViewById(R.id.lblPrinterName);
progressBar = findViewById(R.id.pgBar);
btAdapter = BluetoothAdapter.getDefaultAdapter();
btDevice = btAdapter.getBondedDevices().iterator().next(); // Get first paired device
btnPrint.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "Click");
if (findBluetoothDevice()) {
try {
openBluetoothPrinter();
if(btSocket.isConnected()){
printData();
progressBar.setVisibility(View.GONE);
// disconnectBT();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
}
boolean findBluetoothDevice(){
try{
btAdapter = BluetoothAdapter.getDefaultAdapter();
if(btAdapter==null){
lblPrinterName.setText("No Bluetooth Adapter found");
}
if(btAdapter.isEnabled()){
Intent enableBT = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBT,0);
}
Set<BluetoothDevice> pairedDevice = btAdapter.getBondedDevices();
if(pairedDevice.size()>0){
for(BluetoothDevice pairedDev:pairedDevice){
// My Bluetoth printer name is BTP_F09F1A
if(pairedDev.getName().equals("DPP-350")){
btDevice=pairedDev;
lblPrinterName.setText("Bluetooth Printer Attached: "+pairedDev.getName());
Log.d(TAG, "findBluetoothDevice: " + pairedDev.getName() + " " + pairedDev.getAddress());
// break;
return true;
}
}
} else {
lblPrinterName.setText("Bluetooth Printer Attached");
return false;
}
}catch(Exception ex){
ex.printStackTrace();
return false;
}
return false;
}
void openBluetoothPrinter() throws IOException {
try{
//Standard uuid from string //
UUID uuidString = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
btSocket=btDevice.createRfcommSocketToServiceRecord(uuidString);
btSocket.connect();
outputStream = btSocket.getOutputStream();
inputStream = btSocket.getInputStream();
Log.d(TAG, "openBluetoothPrinter: " + btSocket.isConnected());
beginListenData();
} catch (Exception ex){
ex.printStackTrace();
}
}
void beginListenData(){
try{
final Handler handler =new Handler();
final byte delimiter=10;
stopWorker = false;
readBufferPosition = 0;
readBuffer = new byte[1024];
thread = new Thread(new Runnable() {
@Override
public void run() {
while (!Thread.currentThread().isInterrupted() && !stopWorker){
try{
int byteAvailable = inputStream.available();
if(byteAvailable>0){
byte[] packetByte = new byte[byteAvailable];
inputStream.read(packetByte);
for(int i=0; i<byteAvailable; i++){
byte b = packetByte[i];
if(b==delimiter){
byte[] encodedByte = new byte[readBufferPosition];
System.arraycopy(
readBuffer,0,
encodedByte,0,
encodedByte.length
);
final String data = new String(encodedByte,"US-ASCII");
readBufferPosition=0;
handler.post(new Runnable() {
@Override
public void run() {
lblPrinterName.setText(data);
}
});
}else{
readBuffer[readBufferPosition++]=b;
}
}
}
}catch(Exception ex){
stopWorker=true;
}
}
}
});
thread.start();
}catch (Exception ex){
ex.printStackTrace();
}
}
void printData() throws IOException {
try {
// String msg = textBox.getText().toString();
String msg = "I am printing";
msg+="\n";
outputStream.write(msg.getBytes());
progressBar.setVisibility(View.VISIBLE);
// lblPrinterName.setText("Printing Text...");
} catch (Exception ex){
progressBar.setVisibility(View.GONE);
ex.printStackTrace();
}
}
// Disconnect Printer //
void disconnectBT() throws IOException {
try {
stopWorker=true;
outputStream.close();
inputStream.close();
btSocket.close();
lblPrinterName.setText("Printer Disconnected.");
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
У меня нет других bluetooth-принтеров для тестирования.Отправь меня в путь.