aaronmarino
aaronmarino

Reputation: 4002

Can't print from device

I've followed the tutorial on the cloud print website and created a Print activity by copy and pasting the example code.

I'm trying to print an image from the MediaStore but when I get as far as the print screen nothing happens after I press the 'Print' button.

This is the code I'm using to call the 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);

The Uri being logged looks like content://media/external/images/media/26848

The Logcat output when I press the print button is

[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)

Edit: I've tested on a couple of other devices and I don't get the above log output, so it may not be related. However, the result is the same on every device; when I press the print button in the webview nothing happens.

Upvotes: 2

Views: 367

Answers (1)

zarkiel
zarkiel

Reputation: 41

Add the @JavascriptInterface in the methods of PrintDialogJavaScriptInterface class.

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();
        }
    }
}

Upvotes: 4

Related Questions