80,490
社区成员
发帖
与我相关
我的任务
分享//调用
WifiPrinterService wifiprinter = new WifiPrinterService("192.168.0.1", 10000, "GBK");
wifiprinter.printText("\t\t Text to The Printer");
public class WifiPrinterService {
// 定义编码方式
private static String encoding = null;
private String ip;
private int port;
private Socket sock = null;
// 通过socket流进行读写
private OutputStream socketOut = null;
private OutputStreamWriter writer = null;
public Handler myHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
Bundle bundle = msg.getData();
if (msg.what == 0x100) {
sock = (Socket) msg.obj;
}
}
};
public WifiPrinterService(String ip, int port, String encoding) {
try {
this.ip = ip;
this.port = port;
boolean isSocketConnect = false;
if (sock != null) {
closeIOAndSocket();
} else {
WifiConn.start();
}
sock.setSoTimeout(1000 * 3); //sock对象为null异常
socketOut = new DataOutputStream(sock.getOutputStream());
this.encoding = encoding;
writer = new OutputStreamWriter(socketOut, encoding);
isSocketConnect = true;
} catch (Exception e) {
Log.e("king", e.toString());
}
}
Thread WifiConn = new Thread() {
@Override
public void run() {
try {
Socket sock = new Socket(ip, port);
Message msg = new Message();
msg.what = 0x100;
msg.obj = sock;
myHandler.sendMessage(msg);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
};
/**
* 打印文字
*/
public void printText(String text) throws IOException {
String s = text;
byte[] content = s.getBytes("gbk");
socketOut.write(content);
socketOut.flush();
}
}