android 蓝牙打印和网络打印

打印设置的一些常量

public static final byte[][] byteCommands = {
    	{ 0x1b, 0x40 },// 复位打印机
        { 0x1b, 0x4d, 0x00 },// 标准ASCII字体
        { 0x1b, 0x4d, 0x01 },// 压缩ASCII字体
        { 0x1d, 0x21, 0x00 },// 字体不放大
        { 0x1d, 0x21, 0x11 },// 宽高加倍
        { 0x1b, 0x45, 0x00 },// 取消加粗模式
        { 0x1b, 0x45, 0x01 },// 选择加粗模式
        { 0x1b, 0x7b, 0x00 },// 取消倒置打印
        { 0x1b, 0x7b, 0x01 },// 选择倒置打印
        { 0x1d, 0x42, 0x00 },// 取消黑白反显
        { 0x1d, 0x42, 0x01 },// 选择黑白反显
        { 0x1b, 0x56, 0x00 },// 取消顺时针旋转90°
        { 0x1b, 0x56, 0x01 },// 选择顺时针旋转90°
        { 0x1b, 0x69}// 选择顺时针旋转90°
    };

 随着移动互联网发展,很多工作可能会使用移动设备进行办公。那么使用打印机就会变的频繁。   现在打印 一般会分为以下几个类型   蓝牙打印,网络打印,驱动打印

   1.蓝牙打印

    1.1  搜索蓝牙设备

    1.2  和蓝牙设备建立连接

    1.3  如果连接成功 则打印相应内容 和 命令(可以控制字体大小 等等一些指令)

    1.4  还可记住该台设备的蓝牙mac,下次可直接连接该设备进行打印

    先来分享下 打印命令(对大部分机器还是适用,可能部分厂商有不同的命令。可以先用这个命令试试,不行找厂商要)

下面写了个蓝牙连接的demo  需要用到 可以参考下

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
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.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.widget.Toast;

public class BlueActivity extends Activity {

	private ArrayList<BluetoothDevice> mDeviceList;
	private BluetoothAdapter mBlueAdapter;
	private BluetoothSocket mBlueSocket;
	private OutputStream mOutputStream = null;
	private boolean mIsConnect = false;

	public static final byte[][] byteCommands = { { 0x1b, 0x40 },// 复位打印机
			{ 0x1b, 0x4d, 0x00 },// 标准ASCII字体
			{ 0x1b, 0x4d, 0x01 },// 压缩ASCII字体
			{ 0x1d, 0x21, 0x00 },// 字体不放大
			{ 0x1d, 0x21, 0x11 },// 宽高加倍
			{ 0x1b, 0x45, 0x00 },// 取消加粗模式
			{ 0x1b, 0x45, 0x01 },// 选择加粗模式
			{ 0x1b, 0x7b, 0x00 },// 取消倒置打印
			{ 0x1b, 0x7b, 0x01 },// 选择倒置打印
			{ 0x1d, 0x42, 0x00 },// 取消黑白反显
			{ 0x1d, 0x42, 0x01 },// 选择黑白反显
			{ 0x1b, 0x56, 0x00 },// 取消顺时针旋转90°
			{ 0x1b, 0x56, 0x01 },// 选择顺时针旋转90°
			{ 0x1b, 0x69 } // 选择顺时针旋转90°
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		// 获取蓝牙适配器
		mBlueAdapter = BluetoothAdapter.getDefaultAdapter();
		// 如果获取的蓝牙适配器为空 说明 该设备不支持蓝牙
		if (mBlueAdapter == null) {
			finish();
		}
		mDeviceList = new ArrayList<BluetoothDevice>();
		initIntentFilter();
	}

	private void initIntentFilter() {
		// 设置广播信息过滤
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
		intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
		intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
		intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
		// 注册广播接收器,接收并处理搜索结果
		registerReceiver(receiver, intentFilter);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		// 注销广播
		unregisterReceiver(receiver);
	}

	/**
	 * 蓝牙广播接收器
	 */
	private BroadcastReceiver receiver = new BroadcastReceiver() {

		ProgressDialog progressDialog = null;

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (BluetoothDevice.ACTION_FOUND.equals(action)) {
				BluetoothDevice device = intent
						.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
				if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
					// 该设备是之前配对设备
				} else {
					// 该设备是没有进行过配对的设备
					mDeviceList.add(device);
				}
			} else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
				progressDialog = ProgressDialog.show(context, "请稍等...",
						"正在搜索蓝牙设备...", true);
			} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED
					.equals(action)) {
				// 蓝牙设备搜索完毕
				progressDialog.dismiss();
			}
		}

	};

	/**
	 * * using the well-known SPP UUID 00001101-0000-1000-8000-00805F9B34FB.
	 * However if you are connecting to an Android peer then please generate
	 * your own unique UUID.
	 * <p>
	 * Requires {@link android.Manifest.permission#BLUETOOTH}
	 * 
	 * @param uuid
	 *            service record uuid to lookup RFCOMM channel
	 * @return a RFCOMM BluetoothServerSocket ready for an outgoing connection
	 * @throws IOException
	 *             on error, for example Bluetooth not available, or
	 *             insufficient permissions
	 * @param device
	 * @return
	 */
	public void connect(BluetoothDevice device) {
		// 蓝牙连接的uuid 注意:蓝牙设备连接必须使用该uuid 上面注释从源码中拷贝出来的
		// 可以看到 using the well-known SPP UUID
		// 00001101-0000-1000-8000-00805F9B34FB.
		// 而且别忘了给使用蓝牙的程序添加所需要的权限
		UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
		try {
			// 根据uuid 获取一个蓝牙socket
			mBlueSocket = device.createRfcommSocketToServiceRecord(uuid);
			// 进行连接
			mBlueSocket.connect();
			// 连接后获取输出流
			mOutputStream = mBlueSocket.getOutputStream();
			// 如果蓝牙还在搜索的话 则停止搜索 (蓝牙搜索比较耗资源)
			if (mBlueAdapter.isDiscovering()) {
				mBlueAdapter.cancelDiscovery();
			}
		} catch (Exception e) {
			Toast.makeText(this, "连接失败!", Toast.LENGTH_SHORT).show();
		}
		mIsConnect = true;
		Toast.makeText(this, device.getName() + "连接成功!", Toast.LENGTH_SHORT)
				.show();
	}

	/**
	 * 打印内容
	 */
	public void printContent() {
		// 如果连接成功
		if (mIsConnect) {
			try {
				String title = "打印的标题";
				//执行其他命令之前  先进行复位
				mOutputStream.write(byteCommands[0]);
				//宽高加倍指令
				mOutputStream.write(byteCommands[4]);
				byte[] titleData = title.getBytes("GB2312");
				mOutputStream.write(titleData, 0, titleData.length);
				
				String content = "这是需要打印的内容 hello word";
				mOutputStream.write(byteCommands[0]);
				//恢复到标准字体
				
				mOutputStream.write(byteCommands[1]);
				byte[] contentData = title.getBytes("GB2312");
				mOutputStream.write(contentData, 0, contentData.length);
				mOutputStream.flush();
			} catch (IOException e) {
				Toast.makeText(this, "打印失败!", Toast.LENGTH_SHORT).show();
			}
		} else {
			Toast.makeText(this, "蓝牙设备为连接,或者连接失败!", Toast.LENGTH_SHORT).show();
		}
	}

}

    上面说到了 基本的连接 和打印内容 打印命令。下面分享记录蓝牙的mac,以及根据蓝牙mac连接设备

   

private void save(BluetoothDevice device) {
		String macAddress = device.getAddress();
		String blueName = device.getName();
		//可以将这两项保存到首选项里面  或者 写文件都行
	}
	
	
private BluetoothDevice getDevice(String macAddress) {
		BluetoothDevice device = mBlueAdapter.getRemoteDevice(macAddress);
		return device;
	}

  也就是下次我们如果还需要连接 上次连接过的设备  就不需要再进行搜索了。  直接将保持的地址和名称拿出来 连接  从而提高了用户体验。 当然 需要进行一系列判断

  从上面来看  蓝牙连接来看,还是有一点问题。  第一就是  蓝牙连接的时候 没使用线程去连接(应该是耗时操作,大家不要学我啊...自己弄个线程和handler)。 第二就是 如果打印比较多的内容 是不是有点蛋疼啊。每次需要切换命令 其实 大家可以封装嘛。(提供个思路  如果有模板或者内容 很多  可以写个 base 基类  提供一些公用的方法呀  比如 打印标题 居中  打印分割符号  计算字节数 等等 尽性发挥自己的想象 打造自己的 模板框架)

   蓝牙说了这么多 再给大家分享点小东西,比如 现在市场上一般的打印小票 都是 58mm和 80mm,

  58mm一行的字节是 32 ,80mm的字节是48,当然还有一些其他用途的打印尺寸,如标签等等 蓝牙打印基本就这些

    2.网络打印

     网络打印就是利用网络连接打印机,打印我们所需的信息。那么网络这块毫无疑问用的socket。

上面蓝牙也有个BluetoothSocket,其实看源码可以知道  BluetoothSocket 就是对socket的一个封装,BluetoothSocket是蓝牙连接的专用的。

   其也不多说 上代码

public void connect() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					SocketAddress ipe = new InetSocketAddress("192.168.181.11", 9100);
					Socket socket = new Socket();
					socket.connect(ipe);
					if (socket.isConnected()) {
						OutputStream outputStream = socket.getOutputStream();
						String title = "打印的标题";
						// 执行其他命令之前 先进行复位
						outputStream.write(byteCommands[0]);
						// 宽高加倍指令
						outputStream.write(byteCommands[4]);
						byte[] titleData = title.getBytes("GB2312");
						outputStream.write(titleData, 0, titleData.length);

						String content = "这是需要打印的内容 hello word";
						outputStream.write(byteCommands[0]);
						// 恢复到标准字体

						outputStream.write(byteCommands[1]);
						byte[] contentData = title.getBytes("GB2312");
						outputStream.write(contentData, 0, contentData.length);
						outputStream.flush();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}).start();
	}

简单粗暴 只需要知道ip和端口(打印机端口如果没做说明 一般情况下为9100)

如果有特殊的 可以看看说明书 或者直接找生产厂家 至于打印内容也可以自行封装 另外用handler 

进行对状态的一些维护 友好的提示用户)

这里再说下蓝牙打印,蓝牙打印 可以同时连接多个 打印机(一般情况下 连2-3个没什么问题,如果多了 

机器可能撑不住 而直接崩溃 ,这和机器的硬件有关。一般情况下也不会连接那么多吧)

网络打印机应该也是一样 ,可以用线程维护 或者用service。

   

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

a3280028

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值