android无线打印

  • Post author:
  • Post category:其他


上一篇文章看了android连接蓝牙打印,现在我们看看android怎么通过无线连接打印机

输入打印机的IP地址和端口就可以连接上打印机了

package com.qizi.app.ui;

import android.Manifest;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.qizi.app.MyApplication;
import com.qizi.app.R;
import com.qizi.app.model.user.UserModel;
import com.qizi.app.ui.bt.CheckWifiConnThread;
import com.qizi.app.ui.bt.Constant;
import com.qizi.app.ui.bt.DeviceConnFactoryManager;
import com.qizi.app.ui.bt.PrintContent;
import com.qizi.app.ui.bt.PrinterCommand;
import com.qizi.app.ui.bt.ThreadPool;
import com.qizi.app.ui.bt.Utils;
import com.qizi.app.util.SharedPreferencesUtil;

import java.util.ArrayList;

import top.brianliu.framework.common.activity.BaseActivity;

import static android.hardware.usb.UsbManager.ACTION_USB_DEVICE_ATTACHED;
import static android.hardware.usb.UsbManager.ACTION_USB_DEVICE_DETACHED;
import static com.qizi.app.ui.bt.Constant.ACTION_USB_PERMISSION;
import static com.qizi.app.ui.bt.Constant.CONN_STATE_DISCONN;
import static com.qizi.app.ui.bt.Constant.MESSAGE_UPDATE_PARAMETER;
import static com.qizi.app.ui.bt.DeviceConnFactoryManager.ACTION_CONN_STATE;
import static com.qizi.app.ui.bt.DeviceConnFactoryManager.ACTION_QUERY_PRINTER_STATE;
import static com.qizi.app.ui.bt.DeviceConnFactoryManager.CONN_STATE_FAILED;
import static com.qizi.app.ui.bt.DeviceConnFactoryManager.DEVICE_ID;
import static com.qizi.app.ui.bt.DeviceConnFactoryManager.STATE;

public class WifiConfigActivity extends BaseActivity implements
        View.OnClickListener

{
    //返回
    private View backView;

    private Button btnSure;

    private EditText etIp,etPort;


    private SharedPreferencesUtil sharedPreferencesUtil;


    /**
     * 连接状态断开
     */
    private static final int CONN_STATE_DISCONN = 0x007;
    /**
     * 使用打印机指令错误
     */
    private static final int PRINTER_COMMAND_ERROR = 0x008;


    /**
     * ESC查询打印机实时状态指令
     */
    private byte[] esc = {0x10, 0x04, 0x02};
    /**
     * CPCL查询打印机实时状态指令
     */
    private byte[] cpcl={0x1b,0x68};
    /**
     * TSC查询打印机状态指令
     */
    private byte[] tsc = {0x1b, '!', '?'};


    private static final int CONN_MOST_DEVICES = 0x11;
    private static final int CONN_PRINTER = 0x12;

    private ThreadPool threadPool;

    private TextView tvConnState;

    private int id = 0;

    private CheckWifiConnThread checkWifiConnThread;//wifi连接线程监听

    private PendingIntent mPermissionIntent;
    private String[] permissions = {
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.BLUETOOTH
    };

    ArrayList<String> per = new ArrayList<>();
    @Override
    public int getContentViewId() {
        return R.layout.activity_wifi_config;
    }

    private static final int REQUEST_CODE = 0x004;

    private Button btnPrint;

    private void initBroadcast() {
        IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);//USB访问权限广播
        filter.addAction(ACTION_USB_DEVICE_DETACHED);//USB线拔出
        filter.addAction(ACTION_QUERY_PRINTER_STATE);//查询打印机缓冲区状态广播,用于一票一控
        filter.addAction(ACTION_CONN_STATE);//与打印机连接状态
        filter.addAction(ACTION_USB_DEVICE_ATTACHED);//USB线插入
        registerReceiver(receiver, filter);

        /*Intent intent = new Intent(ACTION_CONN_STATE);
        intent.putExtra(STATE, CONN_STATE_FAILED);
        intent.putExtra(DEVICE_ID, id);
        MyApplication.getContext().sendBroadcast(intent);*/
    }

    @Override
    public void findViews() {
        backView = findViewById(R.id.back);
        etIp=findViewById(R.id.et_ip);
        etPort=findViewById(R.id.et_port);
        btnSure=findViewById(R.id.btn_sure);
        tvConnState = (TextView) findViewById(R.id.tv_connState);
        btnPrint=findViewById(R.id.btn_print);
    }

    @Override
    public void init() {

        sharedPreferencesUtil = SharedPreferencesUtil.getInstantiation(getApplicationContext());
        etPort.setText(sharedPreferencesUtil.getString("",SharedPreferencesUtil.port));
        etIp.setText(sharedPreferencesUtil.getString("",SharedPreferencesUtil.ip));
        initBroadcast();

        if (threadPool==null)
        {
            threadPool = ThreadPool.getInstantiation();
        }
        threadPool.addSerialTask(new Runnable() {
            @Override
            public void run() {
                if (DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id] == null ||
                        !DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].getConnState()) {
                    mHandler.obtainMessage(CONN_PRINTER).sendToTarget();
                    return;
                }
                if (DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].getCurrentPrinterCommand() == PrinterCommand.TSC) {
                    mHandler.obtainMessage(CheckWifiConnThread.PING_SUCCESS).sendToTarget();
                    // tvConnState.setText("连接状态成功");
                } else {
                    mHandler.obtainMessage(PRINTER_COMMAND_ERROR).sendToTarget();
                }
            }
        });
    }

    private void checkPermission() {
        for (String permission : permissions) {
            if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(this, permission)) {
                per.add(permission);
            }
        }
    }

    private void requestPermission() {
        if (per.size() > 0) {
            String[] p = new String[per.size()];
            ActivityCompat.requestPermissions(this, per.toArray(p), REQUEST_CODE);
        }
    }


    @Override
    public void bundleListener() {
        backView.setOnClickListener(this);
        btnSure.setOnClickListener(this);
        btnPrint.setOnClickListener(this);
    }

    private void print()
    {
        threadPool = ThreadPool.getInstantiation();
        threadPool.addSerialTask(new Runnable() {
            @Override
            public void run() {
                if (DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id] == null ||
                        !DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].getConnState()) {
                    mHandler.obtainMessage(CONN_PRINTER).sendToTarget();
                    return;
                }
                if (DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].getCurrentPrinterCommand() == PrinterCommand.TSC) {
                    DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].sendDataImmediately(PrintContent.getLabel());
                } else {
                    mHandler.obtainMessage(PRINTER_COMMAND_ERROR).sendToTarget();
                }
            }
        });
    }

    private void confirm()
    {

        final String strIp = etIp.getText().toString().trim();
        final String strPort = etPort.getText().toString().trim();
        if (!TextUtils.isEmpty(strIp) && !TextUtils.isEmpty(strPort))
        {
            sharedPreferencesUtil.putString(strIp, Constant.WIFI_CONFIG_IP);
            sharedPreferencesUtil.putInt(Integer.parseInt(strPort), Constant.WIFI_CONFIG_PORT);

            sharedPreferencesUtil.putString("1","connect-set");
            sharedPreferencesUtil.putString(strIp,SharedPreferencesUtil.ip);
            sharedPreferencesUtil.putString(strPort,SharedPreferencesUtil.port);


            Message message = Message.obtain();
            message.what = MESSAGE_UPDATE_PARAMETER;
            Bundle bundle = new Bundle();
            bundle.putString("Ip", strIp);
            bundle.putString("Port", strPort);
            message.setData(bundle);
            mHandler.sendMessage(message);


        }
        else
        {
            Toast.makeText(getApplicationContext(), "保存失败", Toast.LENGTH_SHORT).show();
        }


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.back:{
                finish();
                break;
            }
            case R.id.btn_sure:{
                confirm();
                break;
            }
            case R.id.btn_print:{
                print();
                break;
            }
        }
    }


    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                //USB请求访问权限
                case ACTION_USB_PERMISSION:
                    synchronized (this) {
                        UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                        if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                            if (device != null) {//用户点击授权
                               // usbConn(device);
                            }
                        } else {//用户点击不授权,则无权限访问USB
                           // Log.e(TAG,"No access to USB");
                        }
                    }
                    break;
                //Usb连接断开广播
                case ACTION_USB_DEVICE_DETACHED:
                    UsbDevice usbDevice = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    if (usbDevice.equals( DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].usbDevice())){
                        mHandler.obtainMessage(CONN_STATE_DISCONN).sendToTarget();
                    }
                    break;
                //连接状态
                case ACTION_CONN_STATE:
                    int state = intent.getIntExtra(STATE, -1);
                    int deviceId = intent.getIntExtra(DEVICE_ID, -1);
                    switch (state) {
                        case DeviceConnFactoryManager.CONN_STATE_DISCONNECT:
                            if (id == deviceId) {
                               // Log.e(TAG,"connection is lost");
                                tvConnState.setText(getString(R.string.str_conn_state_disconnect));
                            }
                            break;
                        case DeviceConnFactoryManager.CONN_STATE_CONNECTING:
                            tvConnState.setText(getString(R.string.str_conn_state_connecting));
                            break;
                        case DeviceConnFactoryManager.CONN_STATE_CONNECTED:
                            tvConnState.setText(getString(R.string.str_conn_state_connected) + "\n" + getConnDeviceInfo());
                            break;
                        case CONN_STATE_FAILED:
                            Utils.toast(WifiConfigActivity.this, getString(R.string.str_conn_fail));
                            //wificonn=false;
                            tvConnState.setText(getString(R.string.str_conn_state_disconnect));
                            break;
                        default:
                            break;
                    }
                    break;
                //连续打印,一票一控,防止打印机乱码
                case ACTION_QUERY_PRINTER_STATE:
                   /* if (counts >=0) {
                        if(continuityprint) {
                            printcount++;
                            Utils.toast(MainActivity.this, getString(R.string.str_continuityprinter) + " " + printcount);
                        }
                        if(counts!=0) {
                            sendContinuityPrint();
                        }else {
                            continuityprint=false;
                        }
                    }*/
                    break;
                default:
                    break;
            }
        }
    };


    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case CONN_STATE_DISCONN://断开连接
                    DeviceConnFactoryManager deviceConnFactoryManager=DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id];
                    if (deviceConnFactoryManager!= null&&deviceConnFactoryManager.getConnState()) {
                        DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].closePort(id);
                        Utils.toast(WifiConfigActivity.this,getString(R.string.str_disconnect_success));
                        tvConnState.setText("成功断开连接");
                    }
                    break;
                case PRINTER_COMMAND_ERROR://打印机指令错误
                    Utils.toast(WifiConfigActivity.this, getString(R.string.str_choice_printer_command));
                    tvConnState.setText("请选择正确的打印机指令");
                    break;
                case CONN_PRINTER://未连接打印机
                    Utils.toast(WifiConfigActivity.this, getString(R.string.str_cann_printer));
                    break;
                case MESSAGE_UPDATE_PARAMETER:
                    String strIp = msg.getData().getString("Ip");
                    String strPort = msg.getData().getString("Port");
                    //初始化端口信息
                    new DeviceConnFactoryManager.Build()
                            //设置端口连接方式
                            .setConnMethod(DeviceConnFactoryManager.CONN_METHOD.WIFI)
                            //设置端口IP地址
                            .setIp(strIp)
                            //设置端口ID(主要用于连接多设备)
                            .setId(id)
                            //设置连接的热点端口号
                            .setPort(Integer.parseInt(strPort))
                            .build();
                    threadPool = ThreadPool.getInstantiation();
                    threadPool.addSerialTask(new Runnable() {
                        @Override
                        public void run() {
                            DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].openPort();
                        }
                    });
                    break;
                case CheckWifiConnThread.PING_SUCCESS://WIfi连接成功\

                   // Toast.makeText(getApplicationContext(), "连接成功", Toast.LENGTH_SHORT).show();
                    tvConnState.setText("连接成功");
                    break;
                case CheckWifiConnThread.PING_FAIL://WIfI断开连接

                   // Toast.makeText(getApplicationContext(), "连接失败", Toast.LENGTH_SHORT).show();
                    tvConnState.setText("连接失败");
                    checkWifiConnThread.cancel();
                    checkWifiConnThread=null;
                    mHandler.obtainMessage(CONN_STATE_DISCONN).sendToTarget();
                    break;
                case Constant.tip:
                    String str=(String) msg.obj;
                    Utils.toast(WifiConfigActivity.this,str);
                    break;
                default:
                    new DeviceConnFactoryManager.Build()
                            //设置端口连接方式
                            .setConnMethod(DeviceConnFactoryManager.CONN_METHOD.WIFI)
                            //设置端口IP地址
                            .setIp("192.168.2.227")
                            //设置端口ID(主要用于连接多设备)
                            .setId(id)
                            //设置连接的热点端口号
                            .setPort(9100)
                            .build();
                    threadPool.addSerialTask(new Runnable() {
                        @Override
                        public void run() {
                            DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].openPort();
                        }
                    });
                    break;
            }
        }
    };


    /**
     * 获取当前连接设备信息
     * @return
     */
    private String getConnDeviceInfo() {
        String str = "";
        DeviceConnFactoryManager deviceConnFactoryManager = DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id];
        if (deviceConnFactoryManager != null
                && deviceConnFactoryManager.getConnState()) {
            if ("USB".equals(deviceConnFactoryManager.getConnMethod().toString())) {
                str += "USB\n";
                str += "USB Name: " + deviceConnFactoryManager.usbDevice().getDeviceName();
            } else if ("WIFI".equals(deviceConnFactoryManager.getConnMethod().toString())) {
                str += "WIFI\n";
                str += "IP: " + deviceConnFactoryManager.getIp() + "\t";
                str += "Port: " + deviceConnFactoryManager.getPort();
                checkWifiConnThread=new CheckWifiConnThread(deviceConnFactoryManager.getIp(),mHandler);//开启监听WiFi线程
                checkWifiConnThread.start();
            } else if ("BLUETOOTH".equals(deviceConnFactoryManager.getConnMethod().toString())) {
                str += "BLUETOOTH\n";
                str += "MacAddress: " + deviceConnFactoryManager.getMacAddress();
            } else if ("SERIAL_PORT".equals(deviceConnFactoryManager.getConnMethod().toString())) {
                str += "SERIAL_PORT\n";
                str += "Path: " + deviceConnFactoryManager.getSerialPortPath() + "\t";
                str += "Baudrate: " + deviceConnFactoryManager.getBaudrate();
            }
        }
        return str;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        unregisterReceiver(receiver);

       // DeviceConnFactoryManager.closeAllPort();
        if (threadPool != null) {
            threadPool.stopThreadPool();
        }


    }

}

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#F1F1F1">




    <!--顶部-->
    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="#FFFFFF">
        <top.brianliu.framework.common.view.ImageTextButton
            android:id="@+id/back"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:paddingLeft="13dp"
            android:text=""
            app:image="@drawable/img_btn_back_black"
            app:image_w="16dp"
            app:image_h="17dp"
            app:spacing="13dp"
            android:background="@drawable/item_bg_white"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:textSize="16sp"
            android:textColor="#333333"
            android:text="无线配置"/>
    </FrameLayout>



        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="50dp"
            android:background="#FFFFFF"
            android:orientation="vertical"
            android:paddingLeft="13dp"
            android:paddingRight="13dp"
            android:paddingBottom="60dp">




            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="40dp">

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerVertical="true"
                    android:text="地址"
                    android:textColor="#333333"
                    android:textSize="14sp" />

                <EditText
                    android:id="@+id/et_ip"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:hint="请输入IP"
                    android:layout_centerVertical="true"
                    android:layout_marginLeft="70dp"
                    android:background="@color/transparent"
                    android:text="192.168.123.100"
                    android:gravity="center|center_vertical"
                    android:singleLine="true"
                    android:textColor="#666666"
                    android:textSize="14sp" />



            </RelativeLayout>

            <View
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:background="#F1F1F1" />



            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="40dp">

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerVertical="true"
                    android:text="端口"
                    android:textColor="#333333"
                    android:textSize="14sp" />

                <EditText
                    android:id="@+id/et_port"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:text="9000"
                    android:layout_centerVertical="true"
                    android:layout_marginLeft="70dp"
                    android:background="@color/transparent"
                    android:gravity="center|center_vertical"
                    android:hint="请输入端口"
                    android:singleLine="true"
                    android:textColor="#666666"
                    android:textSize="14sp" />
            </RelativeLayout>

            <View
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:background="#F1F1F1" />

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_marginTop="@dimen/size_20"
                android:layout_height="40dp">

                <Button
                    android:id="@+id/btn_sure"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_alignParentRight="true"
                    android:textSize="14sp"
                    android:textColor="#FFFFFF"
                    android:text="确认"
                    android:background="@drawable/btn_orange_2_bg"/>
            </RelativeLayout>

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_marginTop="@dimen/size_20"
                android:layout_height="40dp">

                <Button
                    android:id="@+id/btn_print"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_alignParentRight="true"
                    android:textSize="14sp"
                    android:textColor="#FFFFFF"
                    android:text="打印测试"
                    android:background="@drawable/btn_orange_2_bg"/>
            </RelativeLayout>

            <TextView
                android:id="@+id/tv_connState"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="12dp"
                android:layout_marginTop="8dp"
                android:text="@string/str_conn_state_disconnect"
                android:textSize="14sp" />


        </LinearLayout>




</RelativeLayout>



版权声明:本文为zx13525079024原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。