您的位置:首页 > 移动开发 > Android开发

Android连接蓝牙打印机实现PDF文档的打印

2015-04-16 19:10 543 查看
目前网上教程与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是否安装

public static boolean appIsInstalled(Context context, String pageName) {
try {
context.getPackageManager().getPackageInfo(pageName, 0);
return true;
} catch (NameNotFoundException e) {
return false;
}
}

2.安装apk

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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: