目前网上教程与Demo介绍的都是蓝牙链接热敏打印机(pos机大小的打印机),若是想经过蓝牙链接平常所见到的打印机,进行打印,这些教程或Demo是作不到的。
android
目前Android的蓝牙并不支持BPP(Basic Printing Profile),因此在Android实现蓝牙打印,经过正常的手段是实现不了的。网上可以搜索的那些教程或demo我都试过了,Google Play上与打印相关的app,也都安装使用过,目前只有PrinterShare能够实现Word、PDF的打印。接下来的的内容就与这个软件有关。缓存
因为Android自己并无提供相关API,打印机厂商也没有提供Android的驱动,若是本身从头开始开发相关功能,会是一项很是浩大的工程。在通过一段时间的折腾与领导的不停催促后,咱们决定使用PrinterShare来实现蓝牙打印功能,使用过支付宝的应该都知道,它会帮助咱们安装一个快捷支付的APP,我采用的是相同的方法。咱们的应用在使用打印功能时,首先判断PrinterShare是否安装,若是没有安装,就先安装该软件,若是已经安装,就调用PrinterShare的打印Activity,而且把文档的路径传递过去。app
1.判断apk是否安装
spa
public static boolean appIsInstalled(Context context, String pageName) { try { context.getPackageManager().getPackageInfo(pageName, 0); return true; } catch (NameNotFoundException e) { return false; } }
2.安装apk
code
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 目录下
教程
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中的缓存目录
支付宝
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开发
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);