我正在研究需要打印到打印機的android應用程序。我決定使用Google雲打印,因爲它似乎很容易設置。最初,我遵循here發現的步驟來集成到Android中。這將起作用,因爲它會打印到我想要的打印機上。但是,這個過程對用戶來說有點涉及。在我的情況下,過程如下:在Android上使用Google雲打印API
- 用戶選擇我已經顯示的打印按鈕旁邊的某些信息。
- 顯示一個對話框,其中會顯示要打印的內容。在ActionBar中有一個按鈕,顯示「打印」。這開始了這個過程。
- 顯示一個新的活動,顯示連接到該用戶Google帳戶的打印機列表。用戶必須選擇一個。
- 顯示一個新頁面,給出打印作業的說明。
- 用戶必須在右上角選擇「打印」。
- 打印作業已啓動並且打印機打印出圖片。
不幸的是,我的客戶不想要這個過程。他們希望用戶在步驟二中單擊「打印」,然後打印照片(步驟1,2和6)。因此,我不能使用Google提供的Intent,我必須使用實際的API。這需要我獲得Google Auth令牌,獲取所需的打印機,然後以這種方式提交打印作業。我執行以下操作:
- 使用Google Play服務爲用戶Gmail帳戶檢索OAuth令牌。
- 獲取使用/ search API調用的打印機列表。
- 使用/ submit API調用提交打印作業。
我已經完成了前兩個。我只是遇到了圖片的實際打印問題。而不是打印圖片,圖片的字節數據正在打印(Base64編碼)。下面是一些代碼,我怎麼我發送了請求:
ContentResolver contentResolver = context.getContentResolver();
try {
InputStream is = contentResolver.openInputStream(uri);
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();
content = Base64.encodeToString(baos.toByteArray(), Base64.DEFAULT);
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + uri.toString(), e);
} catch (IOException e) {
e.printStackTrace();
}
此代碼檢索圖片(變量「URI」是該文件的URI),並把它變成一個Base64編碼的字符串。這與在Google雲打印頁面上提供的PrintDialogActivity中使用的方法相同(鏈接到上面)。以下是我如何發送了起來:
- 網址:http://www.google.com/cloudprint/submit?access_token=[AUTH_TOKEN_GOES_HERE]&cookies=false&printerid=[PRINTER_ID_HERE]
- HTTP方法:POST
- POST參數:[printerId = PRINTER_ID_HERE,標題= TestPrint,則contentType =圖像/ JPEG,能力= {」功能「:[{}]},內容= [Base64編碼數據字符串放在這裏]]
據我所知,這是它應該是如何。打印時,我收到{「success」:true}的回覆。但是,正如我上面所說,它打印出實際的Base64數據字符串。任何幫助,將不勝感激。
編輯:使用下面說的powerje,我設法解決這個問題。而不是使用上面的代碼,我使用了以下內容:
public void submitPrintJobWithFile(String printerId, String title, String token, String filePath, String contentType){
File file = new File(filePath);
// Method that gets the correct headers
List<Header> headers = getHeaders(contentType, token);
// Method that gets the correct post parameters
String url = CLOUDPRINT_URL + PATH_SUBMIT;
List<NameValuePair> postParams = getParams(title, contentType);
String params = "access_token=" + token + "&cookies=false" + "&printerid=" + printerId;
url += params;
response = sendMultipartData(url, file, postParams, headers);
}
private String sendMultipartData(String url, File file, List<NameValuePair> fields, List<Header> headers){
HttpPost post = new HttpPost(url);
MultipartEntity entity = new MultipartEntity();
for(NameValuePair pair : fields){
String name = pair.getName();
String value = pair.getValue();
try{
entity.addPart(name, new StringBody(value));
}catch (UnsupportedEncodingException e){
Log.d(TAG, "Error turning pair (name=" + name + ", value=" + value + ") into StringBody.");
}
entity.addPart("content", new FileBody(file));
post.setEntity(entity);
// Finish HttpClient request here...
}
您能否提供一些關於處理前兩步的工作樣本? – Skiba
我想這樣做,但沒有第3步 我想顯示連接到同一本地網絡的打印機,並支持使用其IP地址搜索打印機 –
你好@ariets可以分享你完成1和2的步驟ü然後 – SaravanaRaja