我已关注tutorial on the cloud print website并通过复制并粘贴示例代码创建了一个打印 Activity 。
我正在尝试从 MediaStore 打印图像,但是当我到达打印屏幕时,按下“打印”按钮后什么也没有发生。
这是我用来调用 Intent 的代码
Intent printIntent = new Intent(GalleryActivity.this, PrintDialogActivity.class);
Uri fileUri = Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, Long.toString(imageId));
Log.d(this, "File Uri:" + fileUri);
printIntent.setDataAndType(fileUri, "image/*");
startActivity(printIntent);
正在记录的 Uri 看起来像 content://media/external/images/media/26848
按下打印按钮时的 Logcat 输出是
[INFO:CONSOLE(1)] "Uncaught TypeError: Object [object Object] has no method 'getType'", source: https://www.google.com/cloudprint/dialog.html (1)
[INFO:CONSOLE(280)] "Uncaught TypeError: Cannot call method 'k' of null", source: https://www.google.com/cloudprint/client/442365700-dialog_mobile.js (280)
编辑:我在其他几个设备上进行了测试,但没有得到上述日志输出,因此它可能不相关。然而,每个设备上的结果都是相同的;当我按下 WebView 中的打印按钮时,什么也没有发生。
最佳答案
在PrintDialogJavaScriptInterface类的方法中添加@JavascriptInterface。
final class PrintDialogJavaScriptInterface {
@JavascriptInterface
public String getType() {
return cloudPrintIntent.getType();
}
@JavascriptInterface
public String getTitle() {
return cloudPrintIntent.getExtras().getString("title");
}
@JavascriptInterface
public String getContent() {
try {
ContentResolver contentResolver = getContentResolver();
InputStream is = contentResolver.openInputStream(cloudPrintIntent.getData());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int n = is.read(buffer);
while (n >= 0) {
baos.write(buffer, 0, n);
n = is.read(buffer);
}
is.close();
baos.flush();
return Base64.encodeToString(baos.toByteArray(), Base64.DEFAULT);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
@JavascriptInterface
public String getEncoding() {
return CONTENT_TRANSFER_ENCODING;
}
@JavascriptInterface
public void onPostMessage(String message) {
if (message.startsWith(CLOSE_POST_MESSAGE_NAME)) {
finish();
}
}
}
关于android - 无法从设备打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27601733/