为了验证项目中的代码没有问题,我将客户的打印流保存到本地文件上进行测试。
权限 <uses-permission android:name="android.permission.INTERNET"/>
public class MainActivity2 extends AppCompatActivity {
TextView tv_print;
InputStream inputStream;
ClearEditText et_ip;
Pos pos;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
tv_print=(TextView)findViewById(R.id.tv_print);
et_ip= (ClearEditText) findViewById(R.id.et_ip);
pos= Pos.newInstance();
tv_print.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
inputStream= getResources().openRawResource(R.raw.read);
//需要在res/raw 写一个read.txt 文件
new Thread(new Runnable() {
@Override
public voidrun() {
//测试 打印
boolean open =pos.Open(et_ip.getText().toString(),9100);
Message message =newMessage();
message.obj= open;
message.what=0;
handler.sendMessage(message);
}
}).start();
}
});
}
boolean open;
Handler handler=new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
switch(msg.what) {
case0:
open= (boolean) msg.obj;
if(open) {
//打印次数 调用
print();
}else
Toast.makeText(MainActivity2.this,"连接失败请查看打印设置ip是否正确", Toast.LENGTH_SHORT).show();
break;
}
return true;
}
});
private void print() {
if(pos==null)pos= Pos.newInstance();
pos.print2(inputStream);
}
}
public class Pos {
//定义编码方式
private staticStringencoding=null;
privateSocketsocket=null;
// 通过socket流进行读写
privateOutputStreamsocketOut=null;
privateOutputStreamWriterwriter=null;
public intNet_ReceiveTimeout=1500;
booleanIFOpen=false;
privatePos() {
super();
}
public staticPos newInstance() {
Pos fragment =new Pos();
return fragment;
}
public boolean Open(String ipaddress,intnetport) {
if(socket==null||socket.isClosed()) {
try{
SocketAddress ipe =newInetSocketAddress(ipaddress, netport);
socket=newSocket();//Socket(ipaddress, netport,true);
socket.connect(ipe);
socket.setSoTimeout(Net_ReceiveTimeout);
//socket.SendTimeout = Net_SendTimeout;
IFOpen=true;
}catch(Exception e) {
e.printStackTrace();
IFOpen=false;
}
}else{
try{
if(!socket.isClosed())socket.close();
SocketAddress ipe =newInetSocketAddress(ipaddress, netport);
socket=newSocket();//Socket(ipaddress, netport,true);
socket.connect(ipe);
socket.setSoTimeout(Net_ReceiveTimeout);
IFOpen=true;
}catch(Exception e) {
e.printStackTrace();
IFOpen=false;
}
}
returnIFOpen;
}
public Pos(String ip,intport, String encoding)throwsIOException {
try{
SocketAddress ipe =new InetSocketAddress(ip, port);
socket=newSocket();//Socket(ipaddress, netport,true);
socket.connect(ipe);
socket.setSoTimeout(Net_ReceiveTimeout);
}catch(Exception e) {
e.printStackTrace();
if(e.getMessage() !=null&& e.getMessage().equals("EHOSTUNREACH")) {
//ip连接不上,连接失败请查看打印设置ip是否正确 No route to host
//Toast.makeText(MyApplication.getInstance().getApplicationContext(), "连接失败请查看打印设置ip是否正确", Toast.LENGTH_SHORT).show();
}else if(e.getMessage() !=null&& e.getMessage().equals("ETIMEDOUT")) {
//链接超时
try{
socket.close();
SocketAddress ipe =newInetSocketAddress(ip, port);
socket=newSocket();//Socket(ipaddress, netport,true);
socket.connect(ipe);
socket.setSoTimeout(Net_ReceiveTimeout);
}catch(Exception e2) {
e.printStackTrace();
}
}
}
}
public void initdate(String encoding) {
try{
socketOut=newDataOutputStream(socket.getOutputStream());
// this.encoding = encoding;
writer=newOutputStreamWriter(socketOut,"GB2312");
//initPos();
}catch(Exception e) {
e.printStackTrace();
}
}
/**
* 关闭IO流和Socket
*
*@throwsIOException
*/
public void close IOAndSocket()throwsIOException {
writer.close();
socketOut.close();
socket.close();
}
/**
* 初始化打印机
*
*@throwsIOException
*/
public void initPos()throws IOException {
writer.write(0x1B);
writer.write(0x40);
writer.flush();
}
/**
* 加粗
*
*@paramflagfalse为不加粗
*@return
*@throwsIOException
*/
public voidbold(booleanflag)throwsIOException {
if(flag) {
//常规粗细
writer.write(0x1B);
writer.write(69);
writer.write(0xF);
writer.flush();
}else{
//加粗
writer.write(0x1B);
writer.write(69);
writer.write(0);
writer.flush();
}
}
/**
* 复位打印机
*/
public static final byte[]RESET= {0x1b,0x40};
public static final byte[]RESET2= {0x1B,0x43,0x21};
public static final byte[]RESET3= {0x1B,0x4E,0x07};
/**
* 左对齐
*/
public static final byte[]ALIGN_LEFT= {0x1b,0x61,0x00};
/**
* 中间对齐
*/
public static final byte[]ALIGN_CENTER= {0x1b,0x61,0x01};
/**
* 右对齐
*/
public static final byte[]ALIGN_RIGHT= {0x1b,0x61,0x02};
/**
* 选择加粗模式
*/
public static final byte[]BOLD= {0x1b,0x45,0x01};
/**
* 取消加粗模式
*/
public static final byte[]BOLD_CANCEL= {0x1b,0x45,0x00};
/**
* 宽高加倍
*/
public static final byte[]DOUBLE_HEIGHT_WIDTH= {0x1d,0x21,0x11};
/**
* 宽加倍
*/
public static final byte[]DOUBLE_WIDTH= {0x1d,0x21,0x10};
/**
* 高加倍
*/
public static final byte[]DOUBLE_HEIGHT= {0x1d,0x21,0x01};
/**
* 字体不放大
*/
public static final byte[]NORMAL= {0x1d,0x21,0x00};
/**
* 设置默认行间距
*/
public static final byte[]LINE_SPACING_DEFAULT= {0x1b,0x32};
/**
* 打印纸一行最大的字节
*/
private static final intLINE_BYTE_SIZE=48;
private static final intLINE_BYTE_SIZE2=110;
/**
* 打印三列时, 中间一列的中心线距离打印纸左侧的距离
*/
private static final intLEFT_LENGTH=16;
public static final intLEFT_RIGHT=12;
public static final intLEFT_RIGHT_ZHEN=27;
private static final intLEFT_RIGHT2=8;
/**
* 打印三列时, 第一列汉字最多显示几个文字
*/
private static final intLEFT_TEXT_MAX_LENGTH=15;
/**
* 获取数据长度
*
*@parammsg
*@return
*/
@SuppressLint("NewApi")
private static intgetBytesLength(String msg) {
returnmsg.getBytes(Charset.forName("GB2312")).length;
}
/**
* 设置打印格式
*
*@paramcommand格式指令
*/
public voidselectCommand(byte[] command) {
try{
socketOut.write(command);
socketOut.flush();
}catch(IOException e) {
e.printStackTrace();
}
}
///
/// 换行(回车)
///
///
publicString CMD_Enter() {
return newStringBuffer().append((char)10).toString();
}
//测试连接打印机
public voidprint(inti,finalMainActivity activity)throwsIOException {
initdate("GB2312");
selectCommand(RESET);
if(i ==1) {//小票打印机
selectCommand(ALIGN_CENTER);
selectCommand(DOUBLE_HEIGHT_WIDTH);
printText("恋商进销存"+ CMD_Enter());
printLine(1);
getCutPagerByte();
closeIOAndSocket();
}else if(i ==2) {//针式打印机
selectCommand(RESET2);
selectCommand(RESET3);
selectCommand(ALIGN_CENTER);
selectCommand(DOUBLE_HEIGHT_WIDTH);
printText("恋商进销存"+ CMD_Enter());
printLine(1);
getCutPaperByte(CUT_PAGE2);
printLocation(1);
printTabSpace(2);
printWordSpace(1);
closeIOAndSocket();
}
}
public static byte[] toByteArray(InputStream input)throwsIOException {
ByteArrayOutputStream output =newByteArrayOutputStream();
byte[] buffer =new byte[4096];
intn =0;
while(-1!= (n = input.read(buffer))) {
output.write(buffer,0, n);
}
returnoutput.toByteArray();
}
public void print2(finalInputStream inputStream) {
newThread(newRunnable() {
@Override
public voidrun() {
try{
initdate("GB2312");
if(inputStream!=null) {
byte[] aa =toByteArray(inputStream);
// printText("Android" + CMD_Enter());
socketOut.write(aa,0, aa.length);
socketOut.flush();
// getCutPagerByte();
closeIOAndSocket();
}
}catch(Exception e){
e.printStackTrace();
}
}
}).start();
}
}
网友评论