Android应用程序从一个蓝牙打印机打印 [英] Android App to print from a BLUETOOTH PRINTER

查看:542
本文介绍了Android应用程序从一个蓝牙打印机打印的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在网上找到的应用程序上单击发送按钮时,打字的东西到文本框中,打印机运行后完美的作品,除了,并在印刷的过程中间停止,程序不会崩溃,但是。我只是好奇,如果我使用了错误的UUID,其实我甚至不知道它是什么。我有这个下面的类,它是运行应用程序所需要的唯一的类,其余的都是XML,与所有三个蓝牙权限;

 包com.example.bluetoothprinter;进口android.app.Activity;
进口android.bluetooth.BluetoothAdapter;
进口android.bluetooth.BluetoothDevice;
进口android.bluetooth.BluetoothSocket;
进口android.content.Intent;
进口android.os.Bundle;
进口android.os.Handler;
进口android.view.View;
进口android.widget.TextView;
进口android.widget.EditText;
进口android.widget.Button;
进口java.io.IOException异常;
进口的java.io.InputStream;
进口java.io.OutputStream中;
进口java.util.Set中;
进口java.util.UUID中;公共类MainActivity延伸活动{//将显示状态
TextView的myLabel;//将让用户输入任何文字打印
的EditText myTextbox;//机器人内置类蓝牙操作
BluetoothAdapter mBluetoothAdapter;
的BluetoothSocket mmSocket;
BluetoothDevice类mmDevice;的OutputStream mmOutputStream;
InputStream的mmInputStream;
螺纹的WorkerThread;字节[] readBuffer;
INT readBufferPosition;
INT计数器;
挥发性布尔stopWorker;@覆盖
公共无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.activity_main);    尝试{        //我们布莱恩具有特定功能的三个按钮
        按钮openButton =(按钮)findViewById(R.id.open);
        按钮sendButton =(按钮)findViewById(R.id.send);
        按钮closeButton =(按钮)findViewById(R.id.close);        myLabel =(的TextView)findViewById(R.id.label);
        myTextbox =(EditText上)findViewById(R.id.entry);        //打开蓝牙连接
        openButton.setOnClickListener(新View.OnClickListener(){
            公共无效的onClick(视图v){
                尝试{
                    findBT();
                    openBT();
                }赶上(IOException异常前){
                }
            }
        });        //发送由用户键入的数据被打印
        sendButton.setOnClickListener(新View.OnClickListener(){
            公共无效的onClick(视图v){
                尝试{
                    送出数据();
                }赶上(IOException异常前){
                }
            }
        });        //关闭蓝牙连接
        closeButton.setOnClickListener(新View.OnClickListener(){
            公共无效的onClick(视图v){
                尝试{
                    closeBT();
                }赶上(IOException异常前){
                }
            }
        });    }赶上(NullPointerException异常五){
        e.printStackTrace();
    }赶上(例外五){
        e.printStackTrace();
    }
}/ *
 *这将找到一个蓝牙打印机设备
 * /
无效findBT(){    尝试{
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();        如果(mBluetoothAdapter == NULL){
            myLabel.setText(无可用的蓝牙适配器);
        }        如果(!mBluetoothAdapter.isEnabled()){
            意图enableBluetooth =新意图(
                    BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBluetooth,0);
        }        SET<&BluetoothDevice类GT; pairedDevices = mBluetoothAdapter
                .getBondedDevices();
        如果(pairedDevices.size()大于0){
            对于(BluetoothDevice类设备:pairedDevices){                // OJL411MY29I911JH是扫描后显示的蓝牙打印机设备的名称
                如果(device.getName()。等于(OJL411MY29I911JH)){
                    mmDevice =设备;
                    打破;
                }
            }
        }
        myLabel.setText(蓝牙设备找到);
    }赶上(NullPointerException异常五){
        e.printStackTrace();
    }赶上(例外五){
        e.printStackTrace();
    }
}/ *
 *尝试打开蓝牙打印机设备的连接
 * /
无效openBT()抛出IOException
    尝试{
        //标准SerialPortService ID
        UUID UUID = UUID.fromString(00001101-0000-1000-8000-00805f9b34fb);
        mmSocket = mmDevice.createRfcommSocketToServiceRecord(UUID);
        mmSocket.connect();
        mmOutputStream = mmSocket.getOutputStream();
        mmInputStream = mmSocket.getInputStream();        beginListenForData();        myLabel.setText(蓝牙开);
    }赶上(NullPointerException异常五){
        e.printStackTrace();
    }赶上(例外五){
        e.printStackTrace();
    }
}/ *
 *打开连接到蓝牙打印机设备后,
 *我们必须倾听,并检查是否被发送的数据进行打印。
 * /
无效beginListenForData(){
    尝试{
        最后的处理程序处理程序=新的处理程序();        //这是ASCII code为一个换行符
        最后一个字节的分隔符= 10;        stopWorker = FALSE;
        readBufferPosition = 0;
        readBuffer =新的字节[1024];        的WorkerThread =新主题(新的Runnable(){
            公共无效的run(){
                而(!Thread.currentThread()。isInterrupted()
                        &功放;&安培; !stopWorker){                    尝试{                        INT参考bytesAvailable = mmInputStream.available();
                        如果(参考bytesAvailable大于0){
                            字节[] = packetBytes新的字节[方bytesAvailable]
                            mmInputStream.read(packetBytes);
                            的for(int i = 0; I<方bytesAvailable;我++){
                                字节B = packetBytes [I]
                                如果(二==分隔符){
                                    字节[] EN codedBytes =新的字节[readBufferPosition]
                                    System.arraycopy(readBuffer,0,
                                            EN codedBytes,0,
                                            EN codedBytes.length);
                                    最终字符串数据=新的String(
                                            EN codedBytes,US-ASCII);
                                    readBufferPosition = 0;                                    handler.post(新的Runnable(){
                                        公共无效的run(){
                                            myLabel.setText(数据);
                                        }
                                    });
                                }其他{
                                    readBuffer [readBufferPosition ++] = B;
                                }
                            }
                        }                    }赶上(IOException异常前){
                        stopWorker = TRUE;
                    }                }
            }
        });        workerThread.start();
    }赶上(NullPointerException异常五){
        e.printStackTrace();
    }赶上(例外五){
        e.printStackTrace();
    }
}/ *
 *这将数据发送到通过蓝牙打印机进行打印
 * /
无效的SendData()抛出IOException
    尝试{        //文本由用户输入
        弦乐味精= myTextbox.getText()的toString()。
        味精+ =\\ n;        mmOutputStream.write(msg.getBytes());        //告诉用户数据被送到
        myLabel.setText(数据发送);    }赶上(NullPointerException异常五){
        e.printStackTrace();
    }赶上(例外五){
        e.printStackTrace();
    }
}/ *
 *关闭蓝牙打印机连接。
 * /
无效closeBT()抛出IOException
    尝试{
        stopWorker = TRUE;
        mmOutputStream.close();
        mmInputStream.close();
        mmSocket.close();
        myLabel.setText(蓝牙关闭);
    }赶上(NullPointerException异常五){
        e.printStackTrace();
    }赶上(例外五){
        e.printStackTrace();
    }
}
}


解决方案

我添加code到的发送数据函数结束时运行closeBT功能。如果不关闭连接,我认为这是挂在发送的过程。

 无效的SendData()抛出IOException
尝试{    //文本由用户输入
    弦乐味精= myTextbox.getText()的toString()。
    味精+ =\\ n;    mmOutputStream.write(msg.getBytes());    //告诉用户数据被送到
    myLabel.setText(数据发送);}赶上(NullPointerException异常五){
    e.printStackTrace();
     }赶上(例外五){
    e.printStackTrace();
   }
}

The app I have found online works flawlessly except when clicking onto the Send Button, after typing something into the textbox, the printer runs, and stops in the middle of the process of printing, program doesn't crash however. I'm just curious if I'm using the wrong UUID, in fact I don't even know what it is. I have this following class, which is the only class needed to run the app, the rest are XML, with all three BLUETOOTH permissions;

package com.example.bluetoothprinter;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.Button;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;

public class MainActivity extends Activity {

// will show the statuses
TextView myLabel;

// will enable user to enter any text to be printed
EditText myTextbox;

// android built in classes for bluetooth operations
BluetoothAdapter mBluetoothAdapter;
BluetoothSocket mmSocket;
BluetoothDevice mmDevice;

OutputStream mmOutputStream;
InputStream mmInputStream;
Thread workerThread;

byte[] readBuffer;
int readBufferPosition;
int counter;
volatile boolean stopWorker;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    try {

        // we are goin to have three buttons for specific functions
        Button openButton = (Button) findViewById(R.id.open);
        Button sendButton = (Button) findViewById(R.id.send);
        Button closeButton = (Button) findViewById(R.id.close);

        myLabel = (TextView) findViewById(R.id.label);
        myTextbox = (EditText) findViewById(R.id.entry);

        // open bluetooth connection
        openButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                try {
                    findBT();
                    openBT();
                } catch (IOException ex) {
                }
            }
        });

        // send data typed by the user to be printed
        sendButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                try {
                    sendData();
                } catch (IOException ex) {
                }
            }
        });

        // close bluetooth connection
        closeButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                try {
                    closeBT();
                } catch (IOException ex) {
                }
            }
        });

    } catch (NullPointerException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

/*
 * This will find a bluetooth printer device
 */
void findBT() {

    try {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        if (mBluetoothAdapter == null) {
            myLabel.setText("No bluetooth adapter available");
        }

        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableBluetooth = new Intent(
                    BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBluetooth, 0);
        }

        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter
                .getBondedDevices();
        if (pairedDevices.size() > 0) {
            for (BluetoothDevice device : pairedDevices) {

                // OJL411MY29I911JH is the name of the bluetooth printer device shown after scan
                if (device.getName().equals("OJL411MY29I911JH")) {
                    mmDevice = device;
                    break;
                }
            }
        }
        myLabel.setText("Bluetooth Device Found");
    } catch (NullPointerException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

/*
 * Tries to open a connection to the bluetooth printer device
 */
void openBT() throws IOException {
    try {
        // Standard SerialPortService ID
        UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
        mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
        mmSocket.connect();
        mmOutputStream = mmSocket.getOutputStream();
        mmInputStream = mmSocket.getInputStream();

        beginListenForData();

        myLabel.setText("Bluetooth Opened");
    } catch (NullPointerException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

/*
 * After opening a connection to bluetooth printer device, 
 * we have to listen and check if a data were sent to be printed.
 */
void beginListenForData() {
    try {
        final Handler handler = new Handler();

        // This is the ASCII code for a newline character
        final byte delimiter = 10;

        stopWorker = false;
        readBufferPosition = 0;
        readBuffer = new byte[1024];

        workerThread = new Thread(new Runnable() {
            public void run() {
                while (!Thread.currentThread().isInterrupted()
                        && !stopWorker) {

                    try {

                        int bytesAvailable = mmInputStream.available();
                        if (bytesAvailable > 0) {
                            byte[] packetBytes = new byte[bytesAvailable];
                            mmInputStream.read(packetBytes);
                            for (int i = 0; i < bytesAvailable; i++) {
                                byte b = packetBytes[i];
                                if (b == delimiter) {
                                    byte[] encodedBytes = new byte[readBufferPosition];
                                    System.arraycopy(readBuffer, 0,
                                            encodedBytes, 0,
                                            encodedBytes.length);
                                    final String data = new String(
                                            encodedBytes, "US-ASCII");
                                    readBufferPosition = 0;

                                    handler.post(new Runnable() {
                                        public void run() {
                                            myLabel.setText(data);
                                        }
                                    });
                                } else {
                                    readBuffer[readBufferPosition++] = b;
                                }
                            }
                        }

                    } catch (IOException ex) {
                        stopWorker = true;
                    }

                }
            }
        });

        workerThread.start();
    } catch (NullPointerException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

/*
 * This will send data to be printed by the bluetooth printer
 */
void sendData() throws IOException {
    try {

        // the text typed by the user
        String msg = myTextbox.getText().toString();
        msg += "\n";

        mmOutputStream.write(msg.getBytes());

        // tell the user data were sent
        myLabel.setText("Data Sent");

    } catch (NullPointerException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

/*
 * Close the connection to bluetooth printer.
 */
void closeBT() throws IOException {
    try {
        stopWorker = true;
        mmOutputStream.close();
        mmInputStream.close();
        mmSocket.close();
        myLabel.setText("Bluetooth Closed");
    } catch (NullPointerException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
}

解决方案

I added code to run closeBT function at the end of the sendData function. if you don't close the connection, I think it is hanging in the process of sending.

void sendData() throws IOException {
try {

    // the text typed by the user
    String msg = myTextbox.getText().toString();
    msg += "\n";

    mmOutputStream.write(msg.getBytes());

    // tell the user data were sent
    myLabel.setText("Data Sent");

}   catch (NullPointerException e) {
    e.printStackTrace();
     } catch (Exception e) {
    e.printStackTrace();
   }
}

这篇关于Android应用程序从一个蓝牙打印机打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆