使用Android中的套接字连接打印表单打印机

时间:2017-04-24 06:24:09

标签: java android sockets printing

我已将套接字连接到打印机,但我无法打印。 Make Connection类与打印机进行套接字连接并打印 使用方法writeFromInputToOutput。我正在读文件并写作 打印机的插座,但打印机上没有打印出来。

以下是我的代码:

    class MakeConnection extends AsyncTask<String, Void, String>{
        Socket sock = null;
        OutputStream oStream = null;
        File file;
        @Override
        protected String doInBackground(String... params) {
            try {
                sock = new Socket(ipAddress, 9100);
            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
                // Do something
                // lollipop and above versions
                folder = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),folderName);
                if(!checkPermissions()){
                    requestPermission();
                }
                 file = new File(folder + "/" + filename /*"/Mypdf/Read.pdf"*/);
            }
            InputStream is = new FileInputStream(file);
                oStream = sock.getOutputStream();
              writeFromInputToOutput(sock,  is, new DataOutputStream(oStream));
            } catch (IOException e) {
                e.printStackTrace();
                Logger.LogError(TAG, e.toString());
                AppToast.showShortToast(mContext, e.toString());
            }
            return "";
        }
        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
        }
    }


    public  void writeFromInputToOutput(Socket socket,InputStream is,  OutputStream os) throws IOException {
        byte[] buffer = new byte[10000];
  try {
            int count = is.read(buffer);
            while (count != -1) {
                String strindRead = Base64.encodeToString(buffer, 0);
                os.write(buffer, 0, count);
                os.write("\r\n".getBytes());
                os.write("PRINT\r\n".getBytes());
                os.write("PRINT\r\n\f".getBytes());
                os.flush();
                Logger.LogError("STRINGREAD", strindRead);
                count = is.read(buffer);
            }
        }
        finally {
            is.close();
            os.close();
            socket.close();
        }
    }

0 个答案:

没有答案