android中使用PrinterShare实现蓝牙打印功能
16lz
2021-01-23
目前网上教程与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是否安装
12345678 | public static boolean appIsInstalled(Context context, String pageName) { try { context.getPackageManager().getPackageInfo(pageName, 0); return true; } catch (NameNotFoundException e) { return false; }} |
2.安装apk
1234 | 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 910111213141516171819202122 | 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中的缓存目录
12345678 | 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
12345678 | 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); |
声明:eoe文章著作权属于作者,受法律保护,转载时请务必以超链接形式附带如下信息
原文作者:灰尘
原文地址:http://my.eoe.cn/isnull/archive/910.html
更多相关文章
- 现代 Android 开发: 利用 Jetpack Compose 及更多精彩功能!
- Android 蓝牙通信开发(一) 搜索蓝牙设备
- Android上最好的第三方浏览器有哪些不错的功能?
- 调用Android自带日历功能(日历列表单、添加一个日历事件)
- Android动态请求权限的工具类(可请求多个,并且功能完善)
- Android 录音与播放功能的简单实例
- QtAndroid详解(4):JNI调用Android系统功能(1)
- 【经验小谈】androidx86虚拟机跟intel-vt冲突 android x86虚拟机
- Chrome for Android 也将具备 Opera Mobile 和 Amazon Silk 那种