Android 将数据发送到蓝牙打印机
我正在使用SimpleBluetoothLibrary访问我的蓝牙打印机。现在我可以搜索可用的设备,从列表中选择蓝牙打印机,连接到打印机。这些部分已完成。但我不知道如何将数据发送到打印机进行打印作业。这是Android 将数据发送到蓝牙打印机,android,bluetooth,Android,Bluetooth,我正在使用SimpleBluetoothLibrary访问我的蓝牙打印机。现在我可以搜索可用的设备,从列表中选择蓝牙打印机,连接到打印机。这些部分已完成。但我不知道如何将数据发送到打印机进行打印作业。这是OnDeviceConnect方法。我从中获得了设备地址。但我想将数据发送到打印机 @Override public void onDeviceConnected(BluetoothDevice device) { //a device i
OnDeviceConnect
方法。我从中获得了设备地址。但我想将数据发送到打印机
@Override
public void onDeviceConnected(BluetoothDevice device) {
//a device is connected so you can now send stuff to it
mTxt.setText("Connection Status:Connected:" + device.getAddress());
Log.d("Mac_Address", device.getAddress());
}
这里有一个从蓝牙发送数据的简单示例,希望对您有所帮助 MainActivity.java
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) {
// MP300 is the name of the bluetooth printer device
if (device.getName().equals("MP300")) {
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();
}
}
}
package com.example.bluetoothprinter;
导入android.app.Activity;
导入android.bluetooth.BluetoothAdapter;
导入android.bluetooth.bluetooth设备;
导入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扩展了活动{
//将显示状态
文本视图myLabel;
//将允许用户输入要打印的任何文本
编辑文本myTextbox;
//android内置蓝牙操作类
蓝牙适配器mBluetoothAdapter;
蓝牙插座;
蓝牙设备;
输出流mmOutputStream;
输入流mmInputStream;
螺纹加工螺纹;
字节[]读取缓冲区;
int-readBufferPosition;
整数计数器;
易变布尔工;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
试一试{
//我们将有三个按钮用于特定功能
按钮打开按钮=(按钮)findViewById(R.id.open);
按钮sendButton=(按钮)findViewById(R.id.send);
按钮关闭按钮=(按钮)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异常){
}
}
});
//发送用户键入的要打印的数据
sendButton.setOnClickListener(新视图.OnClickListener(){
公共void onClick(视图v){
试一试{
sendData();
}捕获(IOEX异常){
}
}
});
//关闭蓝牙连接
closeButton.setOnClickListener(新视图.OnClickListener(){
公共void onClick(视图v){
试一试{
closeBT();
}捕获(IOEX异常){
}
}
});
}捕获(NullPointerException e){
e、 printStackTrace();
}捕获(例外e){
e、 printStackTrace();
}
}
//这将找到蓝牙打印机设备
void findBT(){
试一试{
mBluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
if(mBluetoothAdapter==null){
myLabel.setText(“没有可用的蓝牙适配器”);
}
如果(!mBluetoothAdapter.isEnabled()){
意图启用蓝牙=新意图(
BluetoothAdapter.ACTION\u REQUEST\u ENABLE);
startActivityForResult(启用蓝牙,0);
}
设置pairedDevices=mBluetoothAdapter
.getBondedDevices();
如果(pairedDevices.size()>0){
用于(蓝牙设备:pairedDevices){
//MP300是蓝牙打印机设备的名称
if(device.getName().equals(“MP300”)){
mmDevice=设备;
打破
}
}
}
myLabel.setText(“找到蓝牙设备”);
}捕获(NullPointerException e){
e、 printStackTrace();
}捕获(例外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(“蓝牙打开”);
}捕获(NullPointerException e){
e、 printStackTrace();
}捕获(例外e){
e、 printStackTrace();
}
}
//打开与蓝牙打印机设备的连接后,
//我们必须倾听并检查是否发送了数据进行打印。
void beginListenForData(){
试一试{
最终处理程序=新处理程序();
//这是换行符的ASCII码
最后一个字节分隔符=10;
stopWorker=false;
readBufferPosition=0;
readBuffer=新字节[1024];
workerThread=新线程(new Runnable()){
公开募捐{
而(!Thread.currentThread().isInterrupted()
&&!停车工人){
试一试{
int bytesavable=mmInputStream.available();
如果(字节可用>0){
byte[]packetBytes=新字节[bytesAvailable];
mmInputStream.read(packetBytes);
for(int i=0;i<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="@+id/label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Type here:" />
<EditText
android:id="@+id/entry"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@id/label"
android:background="@android:drawable/editbox_background" />
<Button
android:id="@+id/open"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="@id/entry"
android:layout_marginLeft="10dip"
android:text="Open" />
<Button
android:id="@+id/send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@id/open"
android:layout_toLeftOf="@id/open"
android:text="Send" />
<Button
android:id="@+id/close"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@id/send"
android:layout_toLeftOf="@id/send"
android:text="Close" />
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.bluetoothprinter"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<supports-screens android:anyDensity="true" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>