Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/224.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从android应用程序成功发送数据后,蓝牙打印机未打印数据_Java_Android_Printing_Bluetooth - Fatal编程技术网

Java 从android应用程序成功发送数据后,蓝牙打印机未打印数据

Java 从android应用程序成功发送数据后,蓝牙打印机未打印数据,java,android,printing,bluetooth,Java,Android,Printing,Bluetooth,请帮忙。我正在开发一个简单的蓝牙打印机应用程序,我想打印用户输入的数据。我的代码工作正常,但打印机无法打印数据。 目前我正在使用MTP-U-85蓝牙打印机。 当我从应用程序发送数据时,打印机颜色从绿色变为蓝色。此外,当我连接和断开蓝牙时,颜色在绿色和蓝色、蓝色和绿色之间变化。一切正常,但数据无法打印 我会给你我的密码 import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; impor

请帮忙。我正在开发一个简单的蓝牙打印机应用程序,我想打印用户输入的数据。我的代码工作正常,但打印机无法打印数据。 目前我正在使用MTP-U-85蓝牙打印机。 当我从应用程序发送数据时,打印机颜色从绿色变为蓝色。此外,当我连接和断开蓝牙时,颜色在绿色和蓝色、蓝色和绿色之间变化。一切正常,但数据无法打印

我会给你我的密码

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;

public class MainActivity extends AppCompatActivity {
    // will show the statuses like bluetooth open, close or data sent
    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;

    // needed for communication to bluetooth device / network
    OutputStream mmOutputStream;
    InputStream mmInputStream;
    Thread workerThread;

    byte[] readBuffer;
    int readBufferPosition;
    volatile boolean stopWorker;
    Button openButton ;
    Button sendButton ;
    Button closeButton;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        try {
            // we are going to have three buttons for specific functions
            openButton = findViewById(R.id.open);
            sendButton = findViewById(R.id.send);
            closeButton = findViewById(R.id.close);

// text label and input box
            myLabel = (TextView) findViewById(R.id.label);
            myTextbox = (EditText) findViewById(R.id.entry);

            openButton.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    try {
                        findBT();
                        openBT();
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                }
            });
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }


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


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

    private void closeBT()  throws IOException{

        try {
            stopWorker = true;
            mmOutputStream.close();
            mmInputStream.close();
            mmSocket.close();
            myLabel.setText("Bluetooth Closed");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // this will send text data to be printed by the bluetooth printer
    void sendData() throws IOException {
        try {
//            if(mmOutputStream==null) {
                // the text typed by the user
                EditText myTextbox = (EditText) findViewById(R.id.entry);
                String msg = myTextbox.getText().toString();
                msg += "\n";
                mmOutputStream = mmSocket.getOutputStream();
                mmOutputStream.write(msg.getBytes());

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

        } 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 (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
                                        );

                                        // specify US-ASCII encoding
                                        final String data = new String(encodedBytes, "US-ASCII");
                                        readBufferPosition = 0;

                                        // tell the user data were sent to bluetooth printer device
                                        handler.post(new Runnable() {
                                            public void run() {
                                                myLabel.setText(data);
                                            }
                                        });

                                    } else {
                                        readBuffer[readBufferPosition++] = b;
                                    }
                                }
                            }

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

                    }
                }
            });

            workerThread.start();

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


    private 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) {

                    // RPP300 is the name of the bluetooth printer device
                    // we got this name from the list of paired devices
                    if (device.getAddress().equals("DC:1D:30:35:3E:64")) {
                        mmDevice = device;
                        break;
                    }
                }
            }

            myLabel.setText("Bluetooth device found.");

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


    }
}
导入android.bluetooth.BluetoothAdapter;
导入android.bluetooth.bluetooth设备;
导入android.bluetooth.BluetoothSocket;
导入android.content.Intent;
导入android.os.Handler;
导入android.support.v7.app.AppActivity;
导入android.os.Bundle;
导入android.view.view;
导入android.widget.Button;
导入android.widget.EditText;
导入android.widget.TextView;
导入java.io.IOException;
导入java.io.InputStream;
导入java.io.OutputStream;
导入java.util.Set;
导入java.util.UUID;
公共类MainActivity扩展了AppCompatActivity{
//将显示蓝牙打开、关闭或数据发送等状态
文本视图myLabel;
//将允许用户输入要打印的任何文本
编辑文本myTextbox;
//android内置蓝牙操作类
蓝牙适配器mBluetoothAdapter;
蓝牙插座;
蓝牙设备;
//需要与蓝牙设备/网络进行通信
输出流mmOutputStream;
输入流mmInputStream;
螺纹加工螺纹;
字节[]读取缓冲区;
int-readBufferPosition;
易变布尔工;
按钮打开按钮;
按钮发送按钮;
按钮关闭按钮;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
试一试{
//我们将有三个按钮用于特定功能
openButton=findViewById(R.id.open);
sendButton=findviewbyd(R.id.send);
closeButton=findViewById(R.id.close);
//文本标签和输入框
myLabel=(TextView)findViewById(R.id.label);
myTextbox=(EditText)findViewById(R.id.entry);
openButton.setOnClickListener(新视图.OnClickListener(){
公共void onClick(视图v){
试一试{
findBT();
openBT();
}捕获(IOEX异常){
例如printStackTrace();
}
}
});
}
捕获(例外e)
{
e、 printStackTrace();
}
//发送用户键入的要打印的数据
sendButton.setOnClickListener(新视图.OnClickListener(){
公共void onClick(视图v){
试一试{
sendData();
}捕获(IOEX异常){
例如printStackTrace();
}
}
});
//关闭蓝牙连接
closeButton.setOnClickListener(新视图.OnClickListener(){
公共void onClick(视图v){
试一试{
closeBT();
}捕获(IOEX异常){
例如printStackTrace();
}
}
});
}
私有void closeBT()引发IOException{
试一试{
stopWorker=true;
mmOutputStream.close();
mmInputStream.close();
mmSocket.close();
myLabel.setText(“蓝牙关闭”);
}捕获(例外e){
e、 printStackTrace();
}
}
//这将发送要由蓝牙打印机打印的文本数据
void sendData()引发IOException{
试一试{
//if(mmOutputStream==null){
//用户键入的文本
EditText myTextbox=(EditText)findViewById(R.id.entry);
字符串msg=myTextbox.getText().toString();
msg+=“\n”;
mmOutputStream=mmSocket.getOutputStream();
mmOutputStream.write(msg.getBytes());
//告诉用户数据已发送
setText(“已发送的数据”);
//            }
}捕获(例外e){
e、 printStackTrace();
}
}
//尝试打开与蓝牙打印机设备的连接
void openBT()引发IOException{
试一试{
//标准SerialPortService ID
UUID UUID=UUID.fromString(“000011101-0000-1000-8000-00805f9b34fb”);
mmSocket=mmDevice.createRfcommSocketToServiceRecord(uuid);
mmSocket.connect();
mmOutputStream=mmSocket.getOutputStream();
mmInputStream=mmSocket.getInputStream();
beginListenForData();
myLabel.setText(“蓝牙打开”);
}捕获(例外e){
e、 printStackTrace();
}
}
/*
*打开与蓝牙打印机设备的连接后,
*我们必须倾听并检查是否发送了数据进行打印。
*/
void beginListenForData()
{
试一试{
最终处理程序=新处理程序();
//这是换行符的ASCII码
最后一个字节分隔符=10;
stopWorker=false;
readBufferPosition=0;
readBuffer=新字节[1024];
workerThread=新线程(new Runnable()){
公开募捐{
而(!Thread.currentThread().isInterrupted()&&!stopWorker){
试一试{
int bytesavable=mmInputStream.available();
如果(字节可用>0){
byte[]packetBytes=新字节[bytesAv]
void sendData() throws IOException {
      try {
        if(mmOutputStream==null) {

            EditText myTextbox = (EditText) findViewById(R.id.entry);
            String msg = myTextbox.getText().toString();
            msg += "\n";
            mmOutputStream = mmSocket.getOutputStream();
            mmOutputStream.write(msg.getBytes());
            Thread.sleep(100);    // add this line 
            myLabel.setText("Data sent.");
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}
final String finalBILL = BILL;
        Thread t = new Thread() {
            public void run() {
                try {

                   // This is printer specific code you can comment ==== > Start
                    mmOutputStream.write(finalBILL.getBytes());
                    Thread.sleep(100);
                    mmOutputStream.write(0x1D);
                    mmOutputStream.write(86);
                    mmOutputStream.write(48);
                    mmOutputStream.write(0);


                    //  Clode BT
                    stopWorker = true;
                    mmOutputStream.close();
                    mmInputStream.close();
                    mmSocket.close();


                } catch (Exception e) {
                    Log.e("MainActivity", "Exe ", e);

                }

            }
        };
        t.start();