我要打印的账单通过蓝牙使用以下code, 当我运行的应用程序,第一次它越来越打印,但是当我试了没有得到打印。
包com.sel.bluetooth;
进口java.io.OutputStream中;
进口java.lang.reflect.Method中;
进口android.app.Activity;
进口android.app.Dialog;
进口android.bluetooth.BluetoothAdapter;
进口android.bluetooth.BluetoothDevice;
进口android.bluetooth.BluetoothSocket;
进口android.content.BroadcastReceiver;
进口android.content.Context;
进口android.content.DialogInterface;
进口android.content.Intent;
进口android.content.IntentFilter;
进口android.os.Bundle;
进口android.util.Log;
进口android.widget.Toast;
公共类BluetoothPrint延伸活动{
BluetoothAdapter mBTAdapter;
的BluetoothSocket mBTSocket = NULL;
对话dialogProgress;
字符串BILL,TRANS_ID;
字符串PRINTER_MAC_ID;
最后弦乐ERROR_MESSAGE =有一个错误的打印账单。
@覆盖
公共无效的onCreate(包savedInstanceState){
super.onCreate(savedInstanceState);
尝试 {
// BILL = getIntent()getStringExtra(TO_PRINT);
// TRANS_ID = getIntent()getStringExtra(TRANS_ID)。
// PRINTER_MAC_ID = getIntent()getStringExtra(MAC_ID);
PRINTER_MAC_ID =00:1F:B7:02:8楼:44;
// PRINTER_MAC_ID =00:12:F3:0D:A3:E6;
// TRANS_ID =12345678;
比尔=\ nSale滑编号:12345678++04-08-2011 \ N的;
BILL = BILL +----------------------------------------;
BILL = BILL +\ñ\ N的;
BILL = BILL +总数量:++2.0 \ N的;
BILL = BILL +总价值:++17625.0 \ N的;
BILL = BILL +-----------------------------------------;
mBTAdapter = BluetoothAdapter.getDefaultAdapter();
dialogProgress =新的对话框(BluetoothPrint.this);
尝试 {
如果(mBTAdapter.isDiscovering())
mBTAdapter.cancelDiscovery();
其他
mBTAdapter.startDiscovery();
}赶上(例外五){
Log.e(类,我的Exe,E);
}
的System.out.println(BT搜索状态:
+ mBTAdapter.isDiscovering());
如果(mBTAdapter == NULL){
Toast.makeText(这一点,设备不具有蓝牙功能,
Toast.LENGTH_LONG).show();
完();
} 其他 {
如果(!mBTAdapter.isEnabled()){
意图I =新的意图(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(ⅰ,0);
}
//注册的BroadcastReceiver
IntentFilter的过滤器=新的IntentFilter(
BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver,过滤器); //不要忘了
期间//注销
//的onDestroy
dialogProgress.setTitle(查找打印机......);
dialogProgress
.setOnDismissListener(新DialogInterface.OnDismissListener(){
公共无效onDismiss(DialogInterface对话){
dialog.dismiss();
的setResult(RESULT_CANCELED);
完();
}
});
dialogProgress.show();
}
}赶上(例外五){
Log.e(类,我的Exe,E);
}
}
公共无效printBillToDevice(最后弦乐地址){
新主题(新的Runnable(){
公共无效的run(){
runOnUiThread(新的Runnable(){
公共无效的run(){
dialogProgress.setTitle(连接...);
dialogProgress.show();
}
});
mBTAdapter.cancelDiscovery();
尝试 {
System.out的
.println(************#****连接);
BluetoothDevice类mdevice = mBTAdapter
.getRemoteDevice(地址);
方法M = mdevice.getClass()。GetMethod的(
createRfcommSocket,新的等级[] {int.class});
mBTSocket =(的BluetoothSocket)m.invoke(mdevice,1);
mBTSocket.connect();
OutputStream的OS = mBTSocket.getOutputStream();
os.flush();
os.write(BILL.getBytes());
的System.out.println(BILL);
//mBTSocket.close();
的setResult(RESULT_OK);
完();
}赶上(例外五){
Log.e(类,我的Exe,E);
//Toast.makeText(BluetoothPrint.this,ERROR_MESSAGE,Toast.LENGTH_SHORT).show();
e.printStackTrace();
的setResult(RESULT_CANCELED);
完();
}
runOnUiThread(新的Runnable(){
公共无效的run(){
尝试 {
dialogProgress.dismiss();
}赶上(例外五){
Log.e(类,我的Exe,E);
}
}
});
}
})。开始();
}
@覆盖
保护无效的onDestroy(){
Log.i(目的地,检查Ddest);
super.onDestroy();
尝试 {
如果(dialogProgress!= NULL)
dialogProgress.dismiss();
如果(mBTAdapter!= NULL)
mBTAdapter.cancelDiscovery();
this.unregisterReceiver(mReceiver);
}赶上(例外五){
Log.e(类,我的Exe,E);
}
}
私人最终的BroadcastReceiver mReceiver =新的BroadcastReceiver(){
公共无效的onReceive(上下文的背景下,意图意图){
尝试 {
串动= intent.getAction();
//当发现找到的设备
如果(BluetoothDevice.ACTION_FOUND.equals(动作)){
//从意图获取BluetoothDevice类对象
BluetoothDevice类设备=意图
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
的System.out.println(***+ device.getName()+:
+ device.getAddress());
如果(device.getAddress()。equalsIgnoreCase(PRINTER_MAC_ID)){
mBTAdapter.cancelDiscovery();
dialogProgress.dismiss();
Toast.makeText(BluetoothPrint.this,
device.getName()+打印数据,
Toast.LENGTH_LONG).show();
printBillToDevice(PRINTER_MAC_ID);
Toast.makeText(BluetoothPrint.this,
device.getName()+发现,Toast.LENGTH_LONG)
。显示();
}
}
}赶上(例外五){
Log.e(类,我的Exe,E);
//Toast.makeText(BluetoothPrint.this,ERROR_MESSAGE,Toast.LENGTH_SHORT).show();
}
}
};
@覆盖
公共无效onBack pressed(){
尝试 {
如果(mBTAdapter!= NULL)
mBTAdapter.cancelDiscovery();
this.unregisterReceiver(mReceiver);
}赶上(例外五){
Log.e(类,我的Exe,E);
}
的setResult(RESULT_CANCELED);
完();
}
}
解决方案
下面是perfectely工作code的蓝牙打印机
device_list.xml
< XML版本=1.0编码=UTF-8&GT?;
< LinearLayout中的xmlns:机器人=http://schemas.android.com/apk/res/android
机器人:方向=垂直机器人:layout_width =FILL_PARENT
机器人:layout_height =FILL_PARENT>
< TextView的机器人:ID =@ + ID / title_paired_devices
机器人:layout_width =FILL_PARENT机器人:layout_height =WRAP_CONTENT
机器人:文本=我的文字安卓知名度=水涨船高
机器人:后台=#666机器人:文字颜色=#FFF
机器人:以下属性来=5dip/>
< ListView的机器人:ID =@ + ID / paired_devices
机器人:layout_width =FILL_PARENT机器人:layout_height =WRAP_CONTENT
机器人:stackFromBottom =真正的机器人:layout_weight =1/>
< / LinearLayout中>
device_name.xml
< XML版本=1.0编码=UTF-8&GT?;
< TextView中的xmlns:机器人=http://schemas.android.com/apk/res/android
机器人:layout_width =FILL_PARENT机器人:layout_height =WRAP_CONTENT
机器人:TEXTSIZE =18sp机器人:填充=5dip/>
main.xml中
< XML版本=1.0编码=UTF-8&GT?;
< LinearLayout中的xmlns:机器人=http://schemas.android.com/apk/res/android
机器人:方向=垂直机器人:layout_width =FILL_PARENT
机器人:layout_height =FILL_PARENT>
< TextView的Android的:layout_width =FILL_PARENT
机器人:layout_height =WRAP_CONTENT机器人:文本=@字符串/你好/>
<按钮的android:文本=扫描机器人:ID =@ + ID /扫描
机器人:layout_width =WRAP_CONTENT机器人:layout_height =WRAP_CONTENT>< /按钮>
<按钮的android:文本=打印机器人:ID =@ + ID / MPRINT
机器人:layout_width =WRAP_CONTENT机器人:layout_height =WRAP_CONTENT>< /按钮>
<按钮的android:文本=Dissable机器人:ID =@ + ID / DIS
机器人:layout_width =WRAP_CONTENT机器人:layout_height =WRAP_CONTENT>< /按钮>
< / LinearLayout中>
DeviceListActivity.java
包com.sel code。
进口java.util.Set中;
进口android.app.Activity;
进口android.bluetooth.BluetoothAdapter;
进口android.bluetooth.BluetoothDevice;
进口android.content.Intent;
进口android.os.Bundle;
进口android.util.Log;
进口android.view.View;
进口android.view.Window;
进口android.widget.AdapterView;
进口android.widget.ArrayAdapter;
进口android.widget.ListView;
进口android.widget.TextView;
进口android.widget.AdapterView.OnItemClickListener;
公共类DeviceListActivity扩展活动
{
受保护的静态最终字符串变量=TAG;
私人BluetoothAdapter mBluetoothAdapter;
私人ArrayAdapter<字符串> mPairedDevicesArrayAdapter;
@覆盖
保护无效的onCreate(包mSavedInstanceState)
{
super.onCreate(mSavedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
的setContentView(R.layout.device_list);
的setResult(Activity.RESULT_CANCELED);
mPairedDevicesArrayAdapter =新的ArrayAdapter<字符串>(这一点,R.layout.device_name);
ListView控件mPairedListView =(ListView控件)findViewById(R.id.paired_devices);
mPairedListView.setAdapter(mPairedDevicesArrayAdapter);
mPairedListView.setOnItemClickListener(mDeviceClickListener);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
设置< BluetoothDevice类> mPairedDevices = mBluetoothAdapter.getBondedDevices();
如果(mPairedDevices.size()大于0)
{
findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
对于(BluetoothDevice类mDevice:mPairedDevices)
{
mPairedDevicesArrayAdapter.add(mDevice.getName()+\ N+ mDevice.getAddress());
}
}
其他
{
字符串mNoDevices =无配对; // getResources()的getText(R.string.none_paired)的ToString()。
mPairedDevicesArrayAdapter.add(mNoDevices);
}
}
@覆盖
保护无效的onDestroy()
{
super.onDestroy();
如果(mBluetoothAdapter!= NULL)
{
mBluetoothAdapter.cancelDiscovery();
}
}
私人OnItemClickListener mDeviceClickListener =新OnItemClickListener()
{
公共无效onItemClick(适配器视图<> mAdapterView,查看MVIEW,INT mPosition,长mLong)
{
mBluetoothAdapter.cancelDiscovery();
字符串mDeviceInfo =((TextView中)MVIEW).getText()的toString()。
字符串mDeviceAddress = mDeviceInfo.substring(mDeviceInfo.length() - 17);
Log.v(TAG,DEVICE_ADDRESS+ mDeviceAddress);
捆绑mBundle =新包();
mBundle.putString(DeviceAddress,mDeviceAddress);
意图mBackIntent =新意图();
mBackIntent.putExtras(mBundle);
的setResult(Activity.RESULT_OK,mBackIntent);
完();
}
};
}
Main.java
包com.sel code。
进口java.io.IOException异常;
进口java.io.OutputStream中;
进口java.nio.ByteBuffer中;
进口java.util.Set中;
进口java.util.UUID中;
进口android.app.Activity;
进口android.app.ProgressDialog;
进口android.bluetooth.BluetoothAdapter;
进口android.bluetooth.BluetoothDevice;
进口android.bluetooth.BluetoothSocket;
进口android.content.Intent;
进口android.os.Bundle;
进口android.os.Handler;
进口android.os.Message;
进口android.util.Log;
进口android.view.View;
进口android.view.Window;
进口android.view.WindowManager;
进口android.widget.Button;
进口android.widget.Toast;
公共类主要活动扩展实现Runnable {
受保护的静态最终字符串变量=TAG;
私有静态最终诠释REQUEST_CONNECT_DEVICE = 1;
私有静态最终诠释REQUEST_ENABLE_BT = 2;
按钮MSCAN,MPRINT,mDisc;
BluetoothAdapter mBluetoothAdapter;
私人UUID applicationUUID = UUID
.fromString(00001101-0000-1000-8000-00805F9B34FB);
私人ProgressDialog mBluetoothConnectProgressDialog;
私有的BluetoothSocket mBluetoothSocket;
BluetoothDevice类mBluetoothDevice;
@覆盖
公共无效的onCreate(包mSavedInstanceState){
super.onCreate(mSavedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow()。setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
的setContentView(R.layout.main);
MSCAN =(按钮)findViewById(R.id.Scan);
mScan.setOnClickListener(新View.OnClickListener(){
公共无效的onClick(查看MVIEW){
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
如果(mBluetoothAdapter == NULL){
Toast.makeText(Main.this,消息1,2000年).show();
} 其他 {
如果(!mBluetoothAdapter.isEnabled()){
意图enableBtIntent =新的意图(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent,
REQUEST_ENABLE_BT);
} 其他 {
ListPairedDevices();
意图connectIntent =新的意图(Main.this,
DeviceListActivity.class);
startActivityForResult(connectIntent,
REQUEST_CONNECT_DEVICE);
}
}
}
});
MPRINT =(按钮)findViewById(R.id.mPrint);
mPrint.setOnClickListener(新View.OnClickListener(){
公共无效的onClick(查看MVIEW){
线程t =新的Thread(){
公共无效的run(){
尝试 {
OutputStream的OS = mBluetoothSocket
.getOutputStream();
字符串比尔=;
比尔=\ nInvoice号:ABCDEF28060000005+
+04-08-2011 \ N的;
BILL = BILL
+-----------------------------------------;
BILL = BILL +\ñ\ N的;
BILL = BILL +总数量:++2.0 \ N的;
BILL = BILL +总价值:+
+17625.0 \ N的;
BILL = BILL
+----------------------------------------- \ N的;
os.write(BILL.getBytes());
//这是打印机专用code,你可以发表评论====>开始
//设置高度
INT GS = 29;
os.write(intToByteArray(GS));
INT H = 104;
os.write(intToByteArray(H));
INT N = 162;
os.write(intToByteArray(正));
//设置宽度
INT gs_width = 29;
os.write(intToByteArray(gs_width));
INT W = 119;
os.write(intToByteArray(W));
INT n_width = 2;
os.write(intToByteArray(n_width));
//打印吧code
INT GS1 = 29;
os.write(intToByteArray(GS1));
INT K = 107;
os.write(intToByteArray(K));
INT M = 73;
os.write(intToByteArray(米));
串吧codeVAL =ASDFC028060000005; //HELLO12345678912345012;
的System.out.println(酒吧code长度:
+吧codeVal.length());
INT N1 =吧codeVal.length();
os.write(intToByteArray(N1));
的for(int i = 0; I<酒吧codeVal.length();我++){
os.write((巴codeVal.charAt(我)+).getBytes());
}
//打印机专用code,你可以发表评论====>结束
}赶上(例外五){
Log.e(主,执行,E);
}
}
};
t.start();
}
});
mDisc =(按钮)findViewById(R.id.dis);
mDisc.setOnClickListener(新View.OnClickListener(){
公共无效的onClick(查看MVIEW){
如果(mBluetoothAdapter!= NULL)
mBluetoothAdapter.disable();
}
});
} //的onCreate
@覆盖
保护无效的onDestroy(){
// TODO自动生成方法存根
super.onDestroy();
尝试 {
如果(mBluetoothSocket!= NULL)
mBluetoothSocket.close();
}赶上(例外五){
Log.e(标签,执行,E);
}
}
@覆盖
公共无效onBack pressed(){
尝试 {
如果(mBluetoothSocket!= NULL)
mBluetoothSocket.close();
}赶上(例外五){
Log.e(标签,执行,E);
}
的setResult(RESULT_CANCELED);
完();
}
公共无效onActivityResult(INT mRequest code,INT mResult code,
意图mDataIntent){
super.onActivityResult(mRequest code,mResult code,mDataIntent);
开关(mRequest code){
案例REQUEST_CONNECT_DEVICE:
如果(mResult code == Activity.RESULT_OK){
捆绑mExtra = mDataIntent.getExtras();
串mDeviceAddress = mExtra.getString(DeviceAddress);
Log.v(TAG,来输入地址+ mDeviceAddress);
mBluetoothDevice = mBluetoothAdapter
.getRemoteDevice(mDeviceAddress);
mBluetoothConnectProgressDialog = ProgressDialog.show(这一点,
连接......,mBluetoothDevice.getName()+:
+ mBluetoothDevice.getAddress(),真,假);
螺纹mBlutoothConnectThread =新主题(本);
mBlutoothConnectThread.start();
// pairToDevice(mBluetoothDevice);这种方法被替换
//螺纹进度对话框
}
打破;
案例REQUEST_ENABLE_BT:
如果(mResult code == Activity.RESULT_OK){
ListPairedDevices();
意图connectIntent =新的意图(Main.this,
DeviceListActivity.class);
startActivityForResult(connectIntent,REQUEST_CONNECT_DEVICE);
} 其他 {
Toast.makeText(Main.this,消息,2000年).show();
}
打破;
}
}
私人无效ListPairedDevices(){
设置< BluetoothDevice类> mPairedDevices = mBluetoothAdapter
.getBondedDevices();
如果(mPairedDevices.size()大于0){
对于(BluetoothDevice类mDevice:mPairedDevices){
Log.v(TAG,PairedDevices:+ mDevice.getName()+
+ mDevice.getAddress());
}
}
}
公共无效的run(){
尝试 {
mBluetoothSocket = mBluetoothDevice
.createRfcommSocketToServiceRecord(applicationUUID);
mBluetoothAdapter.cancelDiscovery();
mBluetoothSocket.connect();
mHandler.sendEmptyMessage(0);
}赶上(IOException异常eConnectException){
Log.d(TAG,CouldNotConnectToSocket,eConnectException);
关闭套接字(mBluetoothSocket);
返回;
}
}
私人无效关闭套接字(的BluetoothSocket nOpenSocket){
尝试 {
nOpenSocket.close();
Log.d(TAG,SocketClosed);
}赶上(IOException异常前){
Log.d(TAG,CouldNotCloseSocket);
}
}
私人处理程序mHandler =新的处理程序(){
@覆盖
公共无效的handleMessage(信息MSG){
mBluetoothConnectProgressDialog.dismiss();
Toast.makeText(Main.thisDeviceConnected,5000).show();
}
};
公共静态字节intToByteArray(int值){
byte []的B = ByteBuffer.allocate(4).putInt(值).array();
对于(INT K = 0; K< b.length个; k ++){
的System.out.println(塞尔瓦[+ K +=+0X
+统一codeFormatter.byteToHex(B [K]));
}
返回b [3];
}
公共byte []的SEL(INT VAL){
ByteBuffer的缓冲= ByteBuffer.allocate(2);
buffer.putInt(VAL);
buffer.flip();
返回buffer.array();
}
}
统一codeFormatter.java
包com.sel code。
进口java.io. *;
公共类统一codeFormatter {
静态公共字符串byteToHex(BYTE B){
//返回十六进制字符串重新字节的B presentation
炭hexDigit [] = {'0','1','2','3','4','5','6','7','8','9',
'A','B','C','D','E','F'};
的char []数组= {hexDigit [(B>> 4)及为0x0F],hexDigit [B和;为0x0F]};
返回新的字符串(数组);
}
静态公共字符串charToHex(字符C){
//返回十六进制字符串重新字符的c presentation
字节喜=(字节)(c取代;>→8);
字节LO =(字节)(C&安培; 0xFF的);
返回byteToHex(HI)+ byteToHex(LO);
}
} // 类
I am trying to print the bill through bluetooth using the following code, when I run the app, first time its getting printed, but when I retry its not getting printed.
package com.sel.bluetooth;
import java.io.OutputStream;
import java.lang.reflect.Method;
import android.app.Activity;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
public class BluetoothPrint extends Activity {
BluetoothAdapter mBTAdapter;
BluetoothSocket mBTSocket = null;
Dialog dialogProgress;
String BILL, TRANS_ID;
String PRINTER_MAC_ID;
final String ERROR_MESSAGE = "There has been an error in printing the bill.";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
// BILL = getIntent().getStringExtra("TO_PRINT");
// TRANS_ID = getIntent().getStringExtra("TRANS_ID");
// PRINTER_MAC_ID = getIntent().getStringExtra("MAC_ID");
PRINTER_MAC_ID = "00:1F:B7:02:8F:44";
//PRINTER_MAC_ID = "00:12:F3:0D:A3:E6";
// TRANS_ID="12345678";
BILL = "\nSale Slip No: 12345678" + " " + "04-08-2011\n";
BILL = BILL + "----------------------------------------";
BILL = BILL + "\n\n";
BILL = BILL + "Total Qty:" + " " + "2.0\n";
BILL = BILL + "Total Value:" + " " + "17625.0\n";
BILL = BILL + "-----------------------------------------";
mBTAdapter = BluetoothAdapter.getDefaultAdapter();
dialogProgress = new Dialog(BluetoothPrint.this);
try {
if (mBTAdapter.isDiscovering())
mBTAdapter.cancelDiscovery();
else
mBTAdapter.startDiscovery();
} catch (Exception e) {
Log.e("Class ", "My Exe ", e);
}
System.out.println("BT Searching status :"
+ mBTAdapter.isDiscovering());
if (mBTAdapter == null) {
Toast.makeText(this, "Device has no bluetooth capability",
Toast.LENGTH_LONG).show();
finish();
} else {
if (!mBTAdapter.isEnabled()) {
Intent i = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(i, 0);
}
// Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(
BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter); // Don't forget to
// unregister during
// onDestroy
dialogProgress.setTitle("Finding printer...");
dialogProgress
.setOnDismissListener(new DialogInterface.OnDismissListener() {
public void onDismiss(DialogInterface dialog) {
dialog.dismiss();
setResult(RESULT_CANCELED);
finish();
}
});
dialogProgress.show();
}
} catch (Exception e) {
Log.e("Class ", "My Exe ", e);
}
}
public void printBillToDevice(final String address) {
new Thread(new Runnable() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
dialogProgress.setTitle("Connecting...");
dialogProgress.show();
}
});
mBTAdapter.cancelDiscovery();
try {
System.out
.println("**************************#****connecting");
BluetoothDevice mdevice = mBTAdapter
.getRemoteDevice(address);
Method m = mdevice.getClass().getMethod(
"createRfcommSocket", new Class[] { int.class });
mBTSocket = (BluetoothSocket) m.invoke(mdevice, 1);
mBTSocket.connect();
OutputStream os = mBTSocket.getOutputStream();
os.flush();
os.write(BILL.getBytes());
System.out.println(BILL);
//mBTSocket.close();
setResult(RESULT_OK);
finish();
} catch (Exception e) {
Log.e("Class ", "My Exe ", e);
//Toast.makeText(BluetoothPrint.this, ERROR_MESSAGE, Toast.LENGTH_SHORT).show();
e.printStackTrace();
setResult(RESULT_CANCELED);
finish();
}
runOnUiThread(new Runnable() {
public void run() {
try {
dialogProgress.dismiss();
} catch (Exception e) {
Log.e("Class ", "My Exe ", e);
}
}
});
}
}).start();
}
@Override
protected void onDestroy() {
Log.i("Dest ", "Checking Ddest");
super.onDestroy();
try {
if(dialogProgress != null)
dialogProgress.dismiss();
if (mBTAdapter != null)
mBTAdapter.cancelDiscovery();
this.unregisterReceiver(mReceiver);
} catch (Exception e) {
Log.e("Class ", "My Exe ", e);
}
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
try {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
System.out.println("***" + device.getName() + " : "
+ device.getAddress());
if (device.getAddress().equalsIgnoreCase(PRINTER_MAC_ID)) {
mBTAdapter.cancelDiscovery();
dialogProgress.dismiss();
Toast.makeText(BluetoothPrint.this,
device.getName() + " Printing data",
Toast.LENGTH_LONG).show();
printBillToDevice(PRINTER_MAC_ID);
Toast.makeText(BluetoothPrint.this,
device.getName() + " found", Toast.LENGTH_LONG)
.show();
}
}
} catch (Exception e) {
Log.e("Class ", "My Exe ", e);
//Toast.makeText(BluetoothPrint.this, ERROR_MESSAGE, Toast.LENGTH_SHORT).show();
}
}
};
@Override
public void onBackPressed() {
try {
if (mBTAdapter != null)
mBTAdapter.cancelDiscovery();
this.unregisterReceiver(mReceiver);
} catch (Exception e) {
Log.e("Class ", "My Exe ", e);
}
setResult(RESULT_CANCELED);
finish();
}
}
解决方案
Here is perfectely working code for blue-tooth printer
device_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:id="@+id/title_paired_devices"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:text="My Text" android:visibility="gone"
android:background="#666" android:textColor="#fff"
android:paddingLeft="5dip" />
<ListView android:id="@+id/paired_devices"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:stackFromBottom="true" android:layout_weight="1" />
</LinearLayout>
device_name.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:textSize="18sp" android:padding="5dip" />
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="@string/hello" />
<Button android:text="Scan" android:id="@+id/Scan"
android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
<Button android:text="Print" android:id="@+id/mPrint"
android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
<Button android:text="Dissable" android:id="@+id/dis"
android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
</LinearLayout>
DeviceListActivity.java
package com.sel.code;
import java.util.Set;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
public class DeviceListActivity extends Activity
{
protected static final String TAG = "TAG";
private BluetoothAdapter mBluetoothAdapter;
private ArrayAdapter<String> mPairedDevicesArrayAdapter;
@Override
protected void onCreate(Bundle mSavedInstanceState)
{
super.onCreate(mSavedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.device_list);
setResult(Activity.RESULT_CANCELED);
mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
ListView mPairedListView = (ListView) findViewById(R.id.paired_devices);
mPairedListView.setAdapter(mPairedDevicesArrayAdapter);
mPairedListView.setOnItemClickListener(mDeviceClickListener);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> mPairedDevices = mBluetoothAdapter.getBondedDevices();
if (mPairedDevices.size() > 0)
{
findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
for (BluetoothDevice mDevice : mPairedDevices)
{
mPairedDevicesArrayAdapter.add(mDevice.getName() + "\n" + mDevice.getAddress());
}
}
else
{
String mNoDevices = "None Paired";//getResources().getText(R.string.none_paired).toString();
mPairedDevicesArrayAdapter.add(mNoDevices);
}
}
@Override
protected void onDestroy()
{
super.onDestroy();
if (mBluetoothAdapter != null)
{
mBluetoothAdapter.cancelDiscovery();
}
}
private OnItemClickListener mDeviceClickListener = new OnItemClickListener()
{
public void onItemClick(AdapterView<?> mAdapterView, View mView, int mPosition, long mLong)
{
mBluetoothAdapter.cancelDiscovery();
String mDeviceInfo = ((TextView) mView).getText().toString();
String mDeviceAddress = mDeviceInfo.substring(mDeviceInfo.length() - 17);
Log.v(TAG, "Device_Address " + mDeviceAddress);
Bundle mBundle = new Bundle();
mBundle.putString("DeviceAddress", mDeviceAddress);
Intent mBackIntent = new Intent();
mBackIntent.putExtras(mBundle);
setResult(Activity.RESULT_OK, mBackIntent);
finish();
}
};
}
Main.java
package com.sel.code;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.Set;
import java.util.UUID;
import android.app.Activity;
import android.app.ProgressDialog;
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.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;
public class Main extends Activity implements Runnable {
protected static final String TAG = "TAG";
private static final int REQUEST_CONNECT_DEVICE = 1;
private static final int REQUEST_ENABLE_BT = 2;
Button mScan, mPrint, mDisc;
BluetoothAdapter mBluetoothAdapter;
private UUID applicationUUID = UUID
.fromString("00001101-0000-1000-8000-00805F9B34FB");
private ProgressDialog mBluetoothConnectProgressDialog;
private BluetoothSocket mBluetoothSocket;
BluetoothDevice mBluetoothDevice;
@Override
public void onCreate(Bundle mSavedInstanceState) {
super.onCreate(mSavedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
mScan = (Button) findViewById(R.id.Scan);
mScan.setOnClickListener(new View.OnClickListener() {
public void onClick(View mView) {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
Toast.makeText(Main.this, "Message1", 2000).show();
} else {
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent,
REQUEST_ENABLE_BT);
} else {
ListPairedDevices();
Intent connectIntent = new Intent(Main.this,
DeviceListActivity.class);
startActivityForResult(connectIntent,
REQUEST_CONNECT_DEVICE);
}
}
}
});
mPrint = (Button) findViewById(R.id.mPrint);
mPrint.setOnClickListener(new View.OnClickListener() {
public void onClick(View mView) {
Thread t = new Thread() {
public void run() {
try {
OutputStream os = mBluetoothSocket
.getOutputStream();
String BILL = "";
BILL = "\nInvoice No: ABCDEF28060000005" + " "
+ "04-08-2011\n";
BILL = BILL
+ "-----------------------------------------";
BILL = BILL + "\n\n";
BILL = BILL + "Total Qty:" + " " + "2.0\n";
BILL = BILL + "Total Value:" + " "
+ "17625.0\n";
BILL = BILL
+ "-----------------------------------------\n";
os.write(BILL.getBytes());
//This is printer specific code you can comment ==== > Start
// Setting height
int gs = 29;
os.write(intToByteArray(gs));
int h = 104;
os.write(intToByteArray(h));
int n = 162;
os.write(intToByteArray(n));
// Setting Width
int gs_width = 29;
os.write(intToByteArray(gs_width));
int w = 119;
os.write(intToByteArray(w));
int n_width = 2;
os.write(intToByteArray(n_width));
// Print BarCode
int gs1 = 29;
os.write(intToByteArray(gs1));
int k = 107;
os.write(intToByteArray(k));
int m = 73;
os.write(intToByteArray(m));
String barCodeVal = "ASDFC028060000005";// "HELLO12345678912345012";
System.out.println("Barcode Length : "
+ barCodeVal.length());
int n1 = barCodeVal.length();
os.write(intToByteArray(n1));
for (int i = 0; i < barCodeVal.length(); i++) {
os.write((barCodeVal.charAt(i) + "").getBytes());
}
//printer specific code you can comment ==== > End
} catch (Exception e) {
Log.e("Main", "Exe ", e);
}
}
};
t.start();
}
});
mDisc = (Button) findViewById(R.id.dis);
mDisc.setOnClickListener(new View.OnClickListener() {
public void onClick(View mView) {
if (mBluetoothAdapter != null)
mBluetoothAdapter.disable();
}
});
}// onCreate
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
try {
if (mBluetoothSocket != null)
mBluetoothSocket.close();
} catch (Exception e) {
Log.e("Tag", "Exe ", e);
}
}
@Override
public void onBackPressed() {
try {
if (mBluetoothSocket != null)
mBluetoothSocket.close();
} catch (Exception e) {
Log.e("Tag", "Exe ", e);
}
setResult(RESULT_CANCELED);
finish();
}
public void onActivityResult(int mRequestCode, int mResultCode,
Intent mDataIntent) {
super.onActivityResult(mRequestCode, mResultCode, mDataIntent);
switch (mRequestCode) {
case REQUEST_CONNECT_DEVICE:
if (mResultCode == Activity.RESULT_OK) {
Bundle mExtra = mDataIntent.getExtras();
String mDeviceAddress = mExtra.getString("DeviceAddress");
Log.v(TAG, "Coming incoming address " + mDeviceAddress);
mBluetoothDevice = mBluetoothAdapter
.getRemoteDevice(mDeviceAddress);
mBluetoothConnectProgressDialog = ProgressDialog.show(this,
"Connecting...", mBluetoothDevice.getName() + " : "
+ mBluetoothDevice.getAddress(), true, false);
Thread mBlutoothConnectThread = new Thread(this);
mBlutoothConnectThread.start();
// pairToDevice(mBluetoothDevice); This method is replaced by
// progress dialog with thread
}
break;
case REQUEST_ENABLE_BT:
if (mResultCode == Activity.RESULT_OK) {
ListPairedDevices();
Intent connectIntent = new Intent(Main.this,
DeviceListActivity.class);
startActivityForResult(connectIntent, REQUEST_CONNECT_DEVICE);
} else {
Toast.makeText(Main.this, "Message", 2000).show();
}
break;
}
}
private void ListPairedDevices() {
Set<BluetoothDevice> mPairedDevices = mBluetoothAdapter
.getBondedDevices();
if (mPairedDevices.size() > 0) {
for (BluetoothDevice mDevice : mPairedDevices) {
Log.v(TAG, "PairedDevices: " + mDevice.getName() + " "
+ mDevice.getAddress());
}
}
}
public void run() {
try {
mBluetoothSocket = mBluetoothDevice
.createRfcommSocketToServiceRecord(applicationUUID);
mBluetoothAdapter.cancelDiscovery();
mBluetoothSocket.connect();
mHandler.sendEmptyMessage(0);
} catch (IOException eConnectException) {
Log.d(TAG, "CouldNotConnectToSocket", eConnectException);
closeSocket(mBluetoothSocket);
return;
}
}
private void closeSocket(BluetoothSocket nOpenSocket) {
try {
nOpenSocket.close();
Log.d(TAG, "SocketClosed");
} catch (IOException ex) {
Log.d(TAG, "CouldNotCloseSocket");
}
}
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
mBluetoothConnectProgressDialog.dismiss();
Toast.makeText(Main.this, "DeviceConnected", 5000).show();
}
};
public static byte intToByteArray(int value) {
byte[] b = ByteBuffer.allocate(4).putInt(value).array();
for (int k = 0; k < b.length; k++) {
System.out.println("Selva [" + k + "] = " + "0x"
+ UnicodeFormatter.byteToHex(b[k]));
}
return b[3];
}
public byte[] sel(int val) {
ByteBuffer buffer = ByteBuffer.allocate(2);
buffer.putInt(val);
buffer.flip();
return buffer.array();
}
}
UnicodeFormatter.java
package com.sel.code;
import java.io.*;
public class UnicodeFormatter {
static public String byteToHex(byte b) {
// Returns hex String representation of byte b
char hexDigit[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f' };
char[] array = { hexDigit[(b >> 4) & 0x0f], hexDigit[b & 0x0f] };
return new String(array);
}
static public String charToHex(char c) {
// Returns hex String representation of char c
byte hi = (byte) (c >>> 8);
byte lo = (byte) (c & 0xff);
return byteToHex(hi) + byteToHex(lo);
}
} // class