我有使用 Java 打印文本文件的代码,如下所示。
该程序在 Java 中运行良好,但我希望能够在 Android 中使用此代码,或者,如果这不可能,谁能帮我解决这个问题?我需要使用 Android 打印文本文件,但我不想使用云打印,而是直接从我的程序中打印。
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.event.PrintJobAdapter;
import javax.print.event.PrintJobEvent;
public class Print {
public static void main(String[] args) {
DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
/* locate a print service that can handle it */
PrintService[] pservices = PrintServiceLookup.lookupPrintServices(flavor, aset);
/* create a print job for the chosen service */
int printnbr = 0;
DocPrintJob pj = pservices[printnbr].createPrintJob();
try {
FileInputStream fis = new FileInputStream("C:\\151_Proteam.key");
Doc doc = new SimpleDoc(fis, flavor, null);
PrintJobWatcher pjDone = new PrintJobWatcher(pj);
/* print the doc as specified */
pj.print(doc, aset);
}
catch (Exception ex){
ex.printStackTrace();
}
}
}
这是 Print Job Watcher 类。
import javax.print.DocPrintJob;
import javax.print.event.PrintJobAdapter;
import javax.print.event.PrintJobEvent;
public class PrintJobWatcher {
// true iff it is safe to close the print job's input stream
private boolean done = false;
public PrintJobWatcher(DocPrintJob job) {
// Add a listener to the print job
job.addPrintJobListener(new PrintJobAdapter() {
public void printJobCanceled(PrintJobEvent pje) {
allDone();
}
public void printJobCompleted(PrintJobEvent pje) {
allDone();
}
public void printJobFailed(PrintJobEvent pje) {
allDone();
}
public void printJobNoMoreEvents(PrintJobEvent pje) {
allDone();
}
void allDone() {
synchronized (PrintJobWatcher.this) {
done = true;
PrintJobWatcher.this.notify();
}
}
});
}
public synchronized void waitForDone() {
try {
System.out.println("Checking Printer Status...");
while (!done) {
/*System.out.println(FileUtils.getCurrentTimeForUseInAFileName()
+ " Waiting for the Print Job to Complete...");*/
wait();
}
System.out.println("Print Job Completed.");
} catch (InterruptedException e) {
}
}
}