如何在我的应用程序内获取以前使用Android打印服务的打印机列表?

时间:2019-04-03 17:22:31

标签: android plugins service printing printers

在Android操作系统上通过服务插件(例如步骤1..3)设置打印机后,我的工作流程应为:

  • 按“打印”按钮
  • 显示带有可用打印机的对话框(先前在Android设置中定义)
  • 执行pdf打印

是否可以在我自己的应用程序中获取此可用打印机列表?怎么样?

到目前为止,我通过Google文档运行的最接近的解决方案是在网络预览上打开pdf,然后让Android处理一切。但是,如果可能的话,我不想破坏我的用户体验。选择打印机后,理想的情况是直接打印pdf。

预先感谢

------- STEPS -------

  1. Android打印设置

Android Printing Settings]

  1. 已安装的服务

Installed Services

  1. 打印机列表

Printers List

2 个答案:

答案 0 :(得分:0)

  

是否可以在我自己的应用程序中获取此可用打印机列表?怎么样?

是的,您可以使用PrintServicehttps://developer.android.com/reference/android/printservice/PrintService

  

打印服务负责发现打印机,添加发现的打印机,删除添加的打印机以及更新添加的打印机。

Android文档在使用与打印相关的API方面也有(有些过时,但仍然有用)的课程:https://developer.android.com/training/printing

此示例包括与打印PDF相关的代码:https://developer.android.com/training/printing/custom-docs

文档中的示例代码:

// Connect to the print manager
private fun doPrint() {
    activity?.also { context ->
        // Get a PrintManager instance
        val printManager = context.getSystemService(Context.PRINT_SERVICE) as PrintManager
        // Set job name, which will be displayed in the print queue
        val jobName = "${context.getString(R.string.app_name)} Document"
        // Start a print job, passing in a PrintDocumentAdapter implementation
        // to handle the generation of a print document
        printManager.print(jobName, MyPrintDocumentAdapter(context), null)
    }
}
// Compute print document info
override fun onLayout(
        oldAttributes: PrintAttributes?,
        newAttributes: PrintAttributes,
        cancellationSignal: CancellationSignal?,
        callback: LayoutResultCallback,
        extras: Bundle?
) {
    // Create a new PdfDocument with the requested page attributes
    pdfDocument = PrintedPdfDocument(activity, newAttributes)

    // Respond to cancellation request
    if (cancellationSignal?.isCanceled == true) {
        callback.onLayoutCancelled()
        return
    }

    // Compute the expected number of printed pages
    val pages = computePageCount(newAttributes)

    if (pages > 0) {
        // Return print information to print framework
        PrintDocumentInfo.Builder("print_output.pdf")
                .setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT)
                .setPageCount(pages)
                .build()
                .also { info ->
                    // Content layout reflow is complete
                    callback.onLayoutFinished(info, true)
                }
    } else {
        // Otherwise report an error to the print framework
        callback.onLayoutFailed("Page count calculation failed.")
    }
}

答案 1 :(得分:0)

到目前为止,没有找到合适的解决方案。可能的替代方法是:

  1. 尝试通过服务插件(例如PrintHand)存储的共享首选项访问打印机。

  2. 如果只是想轻松获取打印机的IP地址,并且要在使用带有条形码扫描仪的设备的情况下,可以在打印机上贴上其IP地址标签,然后进行扫描以存储该地址在会话/单个字段上。

我走了第二条路。