目前網上教程與Demo介紹的都是藍牙連接熱敏打印機(pos機大小的打印機),如果想通過藍牙連接日常所見到的打印機,進行打印,這些教程或Demo是做不到的。
目前Android的藍牙並不支持BPP(Basic Printing Profile),所以在Android實現藍牙打印,通過正常的手段是實現不了的。網上能夠搜索的那些教程或demo我都試過了,Google Play上與打印相關的app,也都安裝使用過,目前只有PrinterShare可以實現Word、PDF的打印。接下來的的內容就與這個軟件有關。
由於Android本身並沒有提供相關API,打印機廠商也沒有提供Android的驅動,如果自己從頭開始開發相關功能,會是一項非常浩大的工程。在經過一段時間的折騰與領導的不停催促後,我們決定使用PrinterShare來實現藍牙打印功能,使用過支付寶的應該都知道,它會幫助我們安裝一個快捷支付的APP,我採用的是相同的方法。我們的應用在使用打印功能時,首先判斷PrinterShare是否安裝,如果沒有安裝,就先安裝該軟件,如果已經安裝,就調用PrinterShare的打印Activity,並且把文檔的路徑傳遞過去。
1.判斷apk是否安裝
1 2 3 4 5 6 7 8 |
public static boolean appIsInstalled(Context context, String pageName) { try { context.getPackageManager().getPackageInfo(pageName, 0); return true; } catch (NameNotFoundException e) { return false; } } |
2.安裝apk
1 2 3 4 |
Intent intent = new Intent(Intent.ACTION_VIEW); File file = FileUtils.getAssetFileToCacheDir(activity,"xxx.apk"); intent.setDataAndType(Uri.fromFile(file),"application/vnd.android.package-archive"); activity.startActivity(intent); |
3.把Asset下的apk拷貝到sdcard下 /Android/data/你的包名/cache 目錄下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
publicstatic File getAssetFileToCacheDir(Context context, String fileName) { try { File cacheDir = FileUtils.getCacheDir(context); final String cachePath = cacheDir.getAbsolutePath()+ File.separator + fileName; InputStream is = context.getAssets().open(fileName); File file = new File(cachePath); file.createNewFile(); FileOutputStream fos = new FileOutputStream(file); byte[] temp = newbyte[1024]; int i = 0; while ((i = is.read(temp)) > 0) { fos.write(temp, 0, i); } fos.close(); is.close(); return file; } catch (IOException e) { e.printStackTrace(); } return null; } |
4.獲取sdcard中的緩存目錄
1 2 3 4 5 6 7 8 |
public static File getCacheDir(Context context) { String APP_DIR_NAME = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/"; File dir = new File(APP_DIR_NAME + context.getPackageName() + "/cache/"); if (!dir.exists()) { dir.mkdirs(); } return dir; } |
5.調用printershare打印pdf
1 2 3 4 5 6 7 8 |
Intent intent = new Intent(); ComponentName comp = new ComponentName("com.dynamixsoftware.printershare","com.dynamixsoftware.printershare.ActivityPrintPDF"); intent = new Intent(); intent.setComponent(comp); intent.setAction("android.intent.action.VIEW"); intent.setType("application/pdf"); intent.setData(Uri.fromFile(pdf)); startActivity(intent); |