Android鏈接藍牙打印機實現PDF文檔的打印

    目前網上教程與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);
相關文章
相關標籤/搜索