android 8 打印机驱动(Android 8新版打印机驱动简明教程)

  • android 8 打印机驱动(Android 8新版打印机驱动简明教程)已关闭评论
  • A+
所属分类:打印机驱动安装
摘要

介绍随着移动设备的普及和应用场景的不断拓展,打印机的需求也越来越高。对于安卓系统而言,打印机驱动的开发也愈发重要。本文将介绍如何在Android8新版中开发打印机驱动。Android8打印机驱动开发在Android8中,

介绍

随着移动设备的普及和应用场景的不断拓展,打印机的需求也越来越高。对于安卓系统而言,打印机驱动的开发也愈发重要。本文将介绍如何在Android 8新版中开发打印机驱动。

Android 8打印机驱动开发

在Android 8中,使用PrintManager类实现打印操作。在打印之前,我们需要先获取打印服务和打印设置对象:

PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);

PrintAttributes printAttributes = new PrintAttributes.Builder()

.setMediaSize(PrintAttributes.MediaSize.NA_LETTER)

.setResolution(new PrintAttributes.Resolution("1", PRINT_SERVICE,300,300))

.setColorMode(PrintAttributes.COLOR_MODE_MONOCHROME)

.build();

上述代码中,我们通过PrintManager获取系统打印服务,并通过PrintAttributes定义打印实例的一些参数设置。需要注意的是,在定义MediaSize和Resolution时需要传入对应的ID和context,这里我们传入了PRINT_SERVICE。

接下来,我们需要定义具体的打印处理过程。这里我们以打印文本为例:

PrintDocumentAdapter printAdapter = new PrintDocumentAdapter() {

@Override

public void onStart() {

}

@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(jobName).setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT).build();

callback.onLayoutFinished(pdi, true);

}

@Override

public void onWrite(PageRange[] pages, ParcelFileDescriptor destination, CancellationSignal cancellationSignal, WriteResultCallback callback) {

FileInputStream in = null;

OutputStream out = null;

try {

File file = new File(getFilesDir(), FILE_NAME);

in = new FileInputStream(file);

out = new FileOutputStream(destination.getFileDescriptor());

byte[] buf = new byte[16384];

int size;

while ((size = in.read(buf)) >= 0 && !cancellationSignal.isCanceled()) {

out.write(buf, 0, size);

}

if (cancellationSignal.isCanceled()) {

callback.onWriteCancelled();

} else {

callback.onWriteFinished(new PageRange[]{PageRange.ALL_PAGES});

}

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (Exception e) {

e.printStackTrace();

} finally {

try {

in.close();

out.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

@Override

public void onFinish() {

}

};

以上代码中,我们定义了打印过程的三个步骤:onStart、onLayout和onWrite。这里以打印文本文件为例,在onWrite中将文件内容写入打印机缓冲区即可。

启动打印

完成打印处理后,我们需要通过PrintManager中的print方法启动打印任务:

String jobName = getString(R.string.app_name) + " Document";

printManager.print(jobName, printAdapter, printAttributes);

上述代码中,我们定义了打印任务的名称并启动打印。

结论

通过上述开发流程,我们可以在Android 8中实现打印机驱动的开发。相关详细说明,请参见官方文档。