如何确定打印任务是否已完成?

3
在我的Android应用程序中,我正在尝试打印PDF文档,目前一切正常,以下是我目前用于打印文件的片段:
private void printFile(){
        PrintManager printManager = (PrintManager) this.getSystemService(getApplicationContext().PRINT_SERVICE);
        PrintDocumentAdapter pda = new PrintDocumentAdapter(){

            @Override
            public void onWrite(PageRange[] pages, ParcelFileDescriptor destination, CancellationSignal cancellationSignal, WriteResultCallback callback){
                OutputStream output = null;

                try {
                    output = new FileOutputStream(destination.getFileDescriptor());
                    byte[] buf = _responseBody;
                    output.write(buf);
                    callback.onWriteFinished(new PageRange[]{PageRange.ALL_PAGES});

                } catch (FileNotFoundException ee){
                    //Catch exception
                } catch (Exception e) {
                    //Catch exception
                } finally {
                    try {
                        output.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onLayout(PrintAttributes oldAttributes, PrintAttributes newAttributes, CancellationSignal cancellationSignal, LayoutResultCallback callback, Bundle extras){
                if (cancellationSignal.isCanceled()) {
                    callback.onLayoutCancelled();
                    return;
                }

                PrintDocumentInfo pdi = new PrintDocumentInfo.Builder("Name of file").setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT).build();
                callback.onLayoutFinished(pdi, true);
            }

            @Override
            public void onFinish(){
                System.out.println("PRINT IS FINISHED");
            }
        };



        PrintAttributes printAttrs = new PrintAttributes.Builder().
                setMediaSize(PrintAttributes.MediaSize.ISO_A6).
                setMinMargins(PrintAttributes.Margins.NO_MARGINS).
                build();

        PrintJob printJob = printManager.print(labelID, pda, printAttrs);

    }

但是当打印完成后,我想运行一个方法返回到应用程序的上一个视图,因此我需要捕获它在打印作业完成时触发的事件,有人可以解释如何做或提供任何代码片段将不胜感激。


4
建议您不要等待打印作业完成,而是在print()函数返回后允许用户导航。根据打印机的策略(在设备和打印机上)以及状态(例如卡纸),打印作业可能需要相当长的时间才能完成。 - CommonsWare
1个回答

1

我同意CommonsWare的评论,打印作业可能需要很长时间,在某些情况下可能会无限期地停留在“阻塞”状态。

值得一提的是,在正常的打印成功情况下,onFinish()回调应该可以正常工作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接