适用于 Android 的蓝牙和 WIFI 打印

发布于 2024-10-11 09:05:59 字数 730 浏览 2 评论 0原文

我们需要一台便携式打印机(手持式,这一点很重要),可以通过蓝牙或wifi连接到Android手机。

目前我所知道的:

  • 这次没有适用于Android的标准打印SDK
  • 有一个名为iPrint SDK的非官方SDK。你们有人尝试过通过wifi或蓝牙吗?有效吗?
  • Printershare 还声称是 以编程方式可用。我可以为每部手机一次性支付 5 美元的费用。它有很多支持的格式。您是否尝试过使用任何手持设备?我向他们询问了支持的蓝牙打印机列表(因为它有一个菜单项“搜索 BT 打印机”),但他们没有回答。

我需要知道上面已经问过的问题:

  • 如何从 Android 应用程序进行打印?
  • 您使用什么类型的打印机?
  • 标准android SDK 是否计划包含打印功能?路线图是什么?现在有 Beta 版还是其他版本吗?
  • 如果我们以某种方式(我不这么认为)构建自己的通过蓝牙打印的解决方案,您能推荐标准和协议来检查和学习吗?

We would need a portable printer (handheld, it is important) that can connect to android phone via bluetooth or wifi.

What I know currently:

  • No standard printing SDK available for Android this time
  • There is a non official SDK called iPrint SDK. Have any of you tried it through wifi or bluetooth? Does it work?
  • Printershare also claims to be programmaticly available. It would be ok for me to pay the one time fee $5 for it per phone. It has a lot of supported formats. Have you tried it with any handheld device? I asked them about the list of supported bluetooth printers (since it has a menu item "search for BT printer"), but they did not answered.

What I need to know above the already asked:

  • How do you print from your android app?
  • What kind of printer do you use?
  • Is it planned in the standard android SDK to include printing? What is the roadmap? Is it available now as Beta or something?
  • If we somehow (i dont think so) build own solution for printing via bluetooth, can you recommend standards and protocols to check and learn?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

暖树树初阳… 2024-10-18 09:05:59

Android 4.4 开始,您可以将文档从设备打印到通过 wifi 的硬件打印机。

Android 应用程序现在可以通过 Wi-Fi 或云托管服务(例如 Google 云打印)打印任何类型的内容。在支持打印的应用程序中,用户可以发现可用的打印机、更改纸张尺寸、选择要打印的特定页面以及打印几乎任何类型的文档、图像或文件。

如何启动打印过程的简单示例:

private void doPrint() {
    PrintManager printManager = (PrintManager) getActivity().getSystemService(Context.PRINT_SERVICE);
    printManager.print("My document", new CustomPrintDocumentAdapter(getActivity()), null);
}

其中 CustomPrintDocumentAdapter 扩展 PrintDocumentAdapter

如需了解更多信息,请访问 Android 开发人员

Starting with Android 4.4 you can print documents from a device to a hardware printer via wifi.

Android apps can now print any type of content over Wi-Fi or cloud-hosted services such as Google Cloud Print. In print-enabled apps, users can discover available printers, change paper sizes, choose specific pages to print, and print almost any kind of document, image, or file.

A brief example of how to start the printing process:

private void doPrint() {
    PrintManager printManager = (PrintManager) getActivity().getSystemService(Context.PRINT_SERVICE);
    printManager.print("My document", new CustomPrintDocumentAdapter(getActivity()), null);
}

where CustomPrintDocumentAdapter extends PrintDocumentAdapter.

More information is available on Android Developers.

蓝梦月影 2024-10-18 09:05:59

目前在 Android 上通过蓝牙进行打印是不可能的(据我所知),因为 Android 不支持蓝牙“配置文件”,例如 BPP(基本打印配置文件)、HCRP(硬拷贝替换配置文件)、BIP(基本成像配置文件)等等,这是蓝牙打印使用的常见配置文件。
参考号这个了解打印英国电信简介。

目前,Android 支持 OPP(对象推送配置文件),用于通过蓝牙发送文件。

要在 Android 蓝牙堆栈中实现打印蓝牙配置文件,您可以参考 Sybase-iAnywhere -Blue-SDK-for-Android,它提供了一个 SDK 来将此功能添加到 Android 上现有的 BT 堆栈实现中。

对于 Wifi 打印,市场上有许多应用程序可让您从 Android 手机打印各种文档和图像。请参阅 PrinterShare 了解此类应用。对于 Wifi 打印,您可以使用任何可以通过以太网 (LAN) 连接的打印机。

另请检查启用“Google 云打印”的打印机,该打印机使用云打印到连接在世界任何地方且支持此协议的打印机。这在市场上是相当新的,但在未来几年肯定会受到关注。请查看此处的云打印应用。以及此处的常见问题解答

希望这能帮助您解决一些问题。

Printing via Bluetooth on Android is not possible as of now (as per my knowledge), as Android does not support Bluetooth 'Profiles', such as BPP (Basic Printing Profile), HCRP (Hardcopy Replacement Profile), BIP (Basic Imaging Profile) etc. which are the common profiles used with Bluetooth Printing.
Ref. this to know about Printing BT profiles.

Currently, Android supports OPP (Object Push Profile) which is used to send files over Bluetooth.

To have printing bluetooth profiles implemented within the Bluetooth Stack for Android, you can refer Sybase-iAnywhere-Blue-SDK-for-Android, which provides an SDK to add this functionality to the existing BT stack implementation on Android.

For Wifi printing, there are many apps on the market that allows you to print various documents and images from your Android phone. See PrinterShare for one such app. For Wifi printing, you can use any printer that you can connect over ethernet (LAN).

Also check out printers that are 'Google Cloud Print' enabled, which uses the cloud to print to a printer connected anywhere in the world, that supports this protocol. This is quite new in the market, but something that will definitely gain traction over the coming years. Check out Cloud print app here. and faq here.

Hope this helps take out a few questions off your list.

水溶 2024-10-18 09:05:59

抱歉,我不了解有关使用蓝牙设备进行打印的知识。
但是,我做了一些关于使用 wifi 打印的研究,并将该代码发布在 GitHub 中,如果需要,您可以参考该代码。 Android-wifi-print - GitHub

这是该原型的流程。

  1. 检查连通性。
  2. 如果连接到 WiFi.. 正在存储该 WiFi 配置。
  3. 现在检查我已经有打印机的信息(WiFi打印机的WiFi配置)是否可用。如果可用,我将扫描并获取 WiFi 扫描结果列表并连接到其他内容。它将显示 WiFi 列表并单击该列表,用户将连接到打印机并存储该 WiFi 配置以供将来的打印作业。
  4. 打印作业完成后,我将连接到之前的 WiFi 或移动数据连接。
  5. 现在回到第二步。
  6. 如果用户通过移动数据连接,我只需启用 WiFi 并执行第三步。
  7. 打印作业完成后,我只是禁用 WiFi。这样,我们将连接回移动数据连接。 (这是安卓默认的)。

下面的课程将处理该原型中的所有打印作业。

PrintUtility.class

public class PrintUtility implements Observer {

    private static final int TIME_OUT = 10000;
    private static final int CONNECTION_TIME_OUT = 5000;

    private Activity mActivity;
    private Fragment mFragment = null;

    private WifiConfiguration mPrinterConfiguration;
    private WifiConfiguration mOldWifiConfiguration;
    private WifiManager mWifiManager;
    private WifiScanner mWifiScanner;
    private List<ScanResult> mScanResults = new ArrayList<ScanResult>();

    private PrintManager mPrintManager;
    private List<PrintJob> mPrintJobs;
    private PrintJob mCurrentPrintJob;

    private File pdfFile;
    private String externalStorageDirectory;

    private Handler mPrintStartHandler = new Handler();
    private Handler mPrintCompleteHandler = new Handler();
    private Handler mWifiConnectHandler = new Handler();
    private String connectionInfo;

    private boolean isMobileDataConnection = false;

    private PrintCompleteService mPrintCompleteService;

    //    Observer pattern
    private Observable mObservable;


    public PrintUtility(Activity mActivity, WifiManager mWifiManager, WifiScanner mWifiScanner) {
        this.mActivity = mActivity;
        this.mWifiManager = mWifiManager;
        this.mWifiScanner = mWifiScanner;
        mPrintCompleteService = (PrintCompleteService) mActivity;
        mObservable = ObservableSingleton.getInstance();
        mObservable.attach(this);
    }

    public PrintUtility(Activity mActivity, Fragment mFragment, WifiManager mWifiManager, WifiScanner mWifiScanner) {
        this.mActivity = mActivity;
        this.mFragment = mFragment;
        this.mWifiManager = mWifiManager;
        this.mWifiScanner = mWifiScanner;
        mPrintCompleteService = (PrintCompleteService) mFragment;
        mObservable = ObservableSingleton.getInstance();
        mObservable.attach(this);
    }

    public void downloadAndPrint(String fileUrl, final String fileName) {

        new FileDownloader(mActivity, fileUrl, fileName) {
            @Override
            protected void onPostExecute(Boolean result) {

                if (!result) {
                    mObservable.notifyObserver(true);
                } else {

                    // print flow will come here.

                    try {
                        externalStorageDirectory = Environment.getExternalStorageDirectory().toString();
                        File folder = new File(externalStorageDirectory, Constants.CONTROLLER_PDF_FOLDER);
                        pdfFile = new File(folder, fileName);
                    } catch (Exception e) {
                        mObservable.notifyObserver(true);
                        e.printStackTrace();
                    }

                    print(pdfFile);

                }

            }
        }.execute("");
    }

    public void print(final File pdfFile) {

        this.pdfFile = pdfFile;

        // check connectivity info -> mobile or wifi.
        connectionInfo = Util.connectionInfo(mActivity);

        if (connectionInfo.equalsIgnoreCase(Constants.CONTROLLER_MOBILE)) {
            // follow mobile flow.
            isMobileDataConnection = true;

            if (mWifiManager.isWifiEnabled() == false) {
                mWifiManager.setWifiEnabled(true);
            }

            mWifiManager.startScan();
            setScanResults(mWifiScanner.getScanResults());

            printerConfiguration();

        } else if (connectionInfo.equalsIgnoreCase(Constants.CONTROLLER_WIFI)) {
            // follow wifi flow..

            // this will get current wifiInfo and store it in shared preference.
            Util.storeCurrentWiFiConfiguration(mActivity);

            printerConfiguration();

        } else {
            mObservable.notifyObserver(true);
        }

    }

    private void printerConfiguration() {

        // check printer detail is available or not.
        mPrinterConfiguration = Util.getWifiConfiguration(mActivity, Constants.CONTROLLER_PRINTER);

        if (mPrinterConfiguration == null) {
            // printer configuration is not available.
            // display list of wifi available in an activity

            showWifiListActivity(Constants.REQUEST_CODE_PRINTER);

        } else {
            // get list of wifi available. if printer configuration available then connect it.
            // else.. show list of available wifi nearby.

            boolean isPrinterAvailable = false;

            // scans nearby wifi..
            mWifiManager.startScan();
            setScanResults(mWifiScanner.getScanResults());


            // checks this wifi in scan result list..
            for (int i = 0; i < mScanResults.size(); i++) {
                if (mPrinterConfiguration.SSID.equals("\"" + mScanResults.get(i).SSID + "\"")) {
                    isPrinterAvailable = true;
                    break;
                }
            }

            if (isPrinterAvailable) {

                // connect to printer wifi and show print settings dialog and continue with print flow.
                connectToWifi(mPrinterConfiguration);

                // prints document.
                doPrint();

            } else {
                showWifiListActivity(Constants.REQUEST_CODE_PRINTER);
            }

        }
    }

    private void showWifiListActivity(int requestCode) {
        Intent iWifi = new Intent(mActivity, WifiListActivity.class);
        mActivity.startActivityForResult(iWifi, requestCode);
    }

    private void connectToWifi(WifiConfiguration mWifiConfiguration) {
        mWifiManager.enableNetwork(mWifiConfiguration.networkId, true);
    }

    public void doPrint() {

        try {
            // it is taking some time to connect to printer.. so i used handler.. and waiting for its status.
            mPrintStartHandler.postDelayed(new Runnable() {
                @Override
                public void run() {

                    mPrintStartHandler.postDelayed(this, TIME_OUT);

                    if (mPrinterConfiguration.status == WifiConfiguration.Status.CURRENT) {
                        if (mWifiManager.getConnectionInfo().getSupplicantState() == SupplicantState.COMPLETED) {

                            if (Util.computePDFPageCount(pdfFile) > 0) {
                                printDocument(pdfFile);
                            } else {

                                AlertDialog.Builder alert = new AlertDialog.Builder(mActivity);

                                alert.setMessage("Can't print, Page count is zero.");

                                alert.setNeutralButton("OK", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int i) {
                                        dialog.dismiss();
                                        switchConnection();
                                    }
                                });

                                alert.show();
                            }
                        }
                        mPrintStartHandler.removeCallbacksAndMessages(null);
                    } else {
                        Toast.makeText(mActivity, "Failed to connect to printer!.", Toast.LENGTH_LONG).show();
                        switchConnection();
                        mPrintStartHandler.removeCallbacksAndMessages(null);
                    }
                }
            }, TIME_OUT);
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(mActivity, "Failed to connect to printer!.", Toast.LENGTH_LONG).show();
            switchConnection();
        }
    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    public void printDocument(File pdfFile) {

        mPrintManager = (PrintManager) mActivity.getSystemService(Context.PRINT_SERVICE);

        String jobName = mActivity.getResources().getString(R.string.app_name) + " Document";

        mCurrentPrintJob = mPrintManager.print(jobName, new PrintServicesAdapter(mActivity, mFragment, pdfFile), null);
    }


    @TargetApi(Build.VERSION_CODES.KITKAT)
    public void completePrintJob() {
        mPrintJobs = mPrintManager.getPrintJobs();

        mPrintCompleteHandler.postDelayed(new Runnable() {
            @Override
            public void run() {

                mPrintCompleteHandler.postDelayed(this, CONNECTION_TIME_OUT);

                if (mCurrentPrintJob.getInfo().getState() == PrintJobInfo.STATE_COMPLETED) {

                    // remove that PrintJob from PrintManager.
                    for (int i = 0; i < mPrintJobs.size(); i++) {
                        if (mPrintJobs.get(i).getId() == mCurrentPrintJob.getId()) {
                            mPrintJobs.remove(i);
                        }
                    }

                    // switching back to previous connection..
                    switchConnection();

                    // stops handler..
                    mPrintCompleteHandler.removeCallbacksAndMessages(null);
                } else if (mCurrentPrintJob.getInfo().getState() == PrintJobInfo.STATE_FAILED) {
                    switchConnection();
                    Toast.makeText(mActivity, "Print Failed!", Toast.LENGTH_LONG).show();
                    mPrintCompleteHandler.removeCallbacksAndMessages(null);
                } else if (mCurrentPrintJob.getInfo().getState() == PrintJobInfo.STATE_CANCELED) {
                    switchConnection();
                    Toast.makeText(mActivity, "Print Cancelled!", Toast.LENGTH_LONG).show();
                    mPrintCompleteHandler.removeCallbacksAndMessages(null);
                }

            }
        }, CONNECTION_TIME_OUT);
    }

    public void switchConnection() {
        try {
            if (!isMobileDataConnection) {

                mOldWifiConfiguration = Util.getWifiConfiguration(mActivity, Constants.CONTROLLER_WIFI);

                // get list of wifi available. if wifi configuration available then connect it.
                // else.. show list of available wifi nearby.
                boolean isWifiAvailable = false;

                // scans nearby wifi.
                mWifiManager.startScan();
                setScanResults(mWifiScanner.getScanResults());

                // checks this wifi in scan result list.
                for (int i = 0; i < mScanResults.size(); i++) {
                    if (mOldWifiConfiguration.SSID.equals("\"" + mScanResults.get(i).SSID + "\"")) {
                        isWifiAvailable = true;
                        break;
                    }
                }

                if (isWifiAvailable) {

                    // connect to printer wifi and show print settings dialog and continue with print flow.
                    connectToWifi(mOldWifiConfiguration);

                    mWifiConnectHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mWifiConnectHandler.postDelayed(this, TIME_OUT);
                            if (mOldWifiConfiguration.status == WifiConfiguration.Status.CURRENT) {
                                if (mWifiManager.getConnectionInfo().getSupplicantState() == SupplicantState.COMPLETED) {

                                    try {
                                        mObservable.notifyObserver(true);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }

                                    mWifiConnectHandler.removeCallbacksAndMessages(null);
                                }
                            }
                        }
                    }, TIME_OUT);

                } else {
                    showWifiListActivity(Constants.REQUEST_CODE_WIFI);
                }
            } else {
                mWifiManager.setWifiEnabled(false);
                mObservable.notifyObserver(true);
            }
        } catch (Exception e) {
            mObservable.notifyObserver(true);
            e.printStackTrace();
        }
    }

    public void getPrinterConfigAndPrint() {
        mPrinterConfiguration = Util.getWifiConfiguration(mActivity, Constants.CONTROLLER_PRINTER);
        doPrint();
    }

    public void setScanResults(List<ScanResult> scanResults) {
        this.mScanResults = scanResults;
    }

    public void onPrintCancelled() {
        switchConnection();
    }

    @Override
    public void update() {
        mObservable.detach(this);
    }

    @Override
    public void updateObserver(boolean bool) {

    }

    @Override
    public void updateObserverProgress(int percentage) {

    }

}

在以下链接的帮助下,我创建了这个。

如果您想打印文件,只需调用 print(file)

如果您想下载文件并打印它,
调用 downloadAndPrint(fileUrl, fileName)

Sorry I don't have knowledge about printing using bluetooth devices..
But, I did some research about printing using wifi and posted that code in GitHub, You can refer to that if needed.. Android-wifi-print - GitHub

This is the flow of that prototype.

  1. checks connectivity.
  2. If connected in WiFi.. am storing that WiFi configuration.
  3. Now checking whether I already have printer's information (WiFi configuration of WiFi printer) is available or not. If available, I'll scan and get list of WiFi ScanResults and connects to that else.. It'll showing list of WiFi and clicking on that, user will connect to printer and stores that WiFi configuration for future printing jobs.
  4. After print job completes, I'm connecting to my previous WiFi or Mobile data connection.
  5. Now going back to 2nd step.
  6. If user connected in Mobile data, I'm just enabling WiFi and following 3rd step.
  7. After Print job completes, I'm just disabling WiFi. so that, We'll be connected back to Mobile data connection. (That is android default).

Below class will take care of all printing jobs in that prototype.

PrintUtility.class

public class PrintUtility implements Observer {

    private static final int TIME_OUT = 10000;
    private static final int CONNECTION_TIME_OUT = 5000;

    private Activity mActivity;
    private Fragment mFragment = null;

    private WifiConfiguration mPrinterConfiguration;
    private WifiConfiguration mOldWifiConfiguration;
    private WifiManager mWifiManager;
    private WifiScanner mWifiScanner;
    private List<ScanResult> mScanResults = new ArrayList<ScanResult>();

    private PrintManager mPrintManager;
    private List<PrintJob> mPrintJobs;
    private PrintJob mCurrentPrintJob;

    private File pdfFile;
    private String externalStorageDirectory;

    private Handler mPrintStartHandler = new Handler();
    private Handler mPrintCompleteHandler = new Handler();
    private Handler mWifiConnectHandler = new Handler();
    private String connectionInfo;

    private boolean isMobileDataConnection = false;

    private PrintCompleteService mPrintCompleteService;

    //    Observer pattern
    private Observable mObservable;


    public PrintUtility(Activity mActivity, WifiManager mWifiManager, WifiScanner mWifiScanner) {
        this.mActivity = mActivity;
        this.mWifiManager = mWifiManager;
        this.mWifiScanner = mWifiScanner;
        mPrintCompleteService = (PrintCompleteService) mActivity;
        mObservable = ObservableSingleton.getInstance();
        mObservable.attach(this);
    }

    public PrintUtility(Activity mActivity, Fragment mFragment, WifiManager mWifiManager, WifiScanner mWifiScanner) {
        this.mActivity = mActivity;
        this.mFragment = mFragment;
        this.mWifiManager = mWifiManager;
        this.mWifiScanner = mWifiScanner;
        mPrintCompleteService = (PrintCompleteService) mFragment;
        mObservable = ObservableSingleton.getInstance();
        mObservable.attach(this);
    }

    public void downloadAndPrint(String fileUrl, final String fileName) {

        new FileDownloader(mActivity, fileUrl, fileName) {
            @Override
            protected void onPostExecute(Boolean result) {

                if (!result) {
                    mObservable.notifyObserver(true);
                } else {

                    // print flow will come here.

                    try {
                        externalStorageDirectory = Environment.getExternalStorageDirectory().toString();
                        File folder = new File(externalStorageDirectory, Constants.CONTROLLER_PDF_FOLDER);
                        pdfFile = new File(folder, fileName);
                    } catch (Exception e) {
                        mObservable.notifyObserver(true);
                        e.printStackTrace();
                    }

                    print(pdfFile);

                }

            }
        }.execute("");
    }

    public void print(final File pdfFile) {

        this.pdfFile = pdfFile;

        // check connectivity info -> mobile or wifi.
        connectionInfo = Util.connectionInfo(mActivity);

        if (connectionInfo.equalsIgnoreCase(Constants.CONTROLLER_MOBILE)) {
            // follow mobile flow.
            isMobileDataConnection = true;

            if (mWifiManager.isWifiEnabled() == false) {
                mWifiManager.setWifiEnabled(true);
            }

            mWifiManager.startScan();
            setScanResults(mWifiScanner.getScanResults());

            printerConfiguration();

        } else if (connectionInfo.equalsIgnoreCase(Constants.CONTROLLER_WIFI)) {
            // follow wifi flow..

            // this will get current wifiInfo and store it in shared preference.
            Util.storeCurrentWiFiConfiguration(mActivity);

            printerConfiguration();

        } else {
            mObservable.notifyObserver(true);
        }

    }

    private void printerConfiguration() {

        // check printer detail is available or not.
        mPrinterConfiguration = Util.getWifiConfiguration(mActivity, Constants.CONTROLLER_PRINTER);

        if (mPrinterConfiguration == null) {
            // printer configuration is not available.
            // display list of wifi available in an activity

            showWifiListActivity(Constants.REQUEST_CODE_PRINTER);

        } else {
            // get list of wifi available. if printer configuration available then connect it.
            // else.. show list of available wifi nearby.

            boolean isPrinterAvailable = false;

            // scans nearby wifi..
            mWifiManager.startScan();
            setScanResults(mWifiScanner.getScanResults());


            // checks this wifi in scan result list..
            for (int i = 0; i < mScanResults.size(); i++) {
                if (mPrinterConfiguration.SSID.equals("\"" + mScanResults.get(i).SSID + "\"")) {
                    isPrinterAvailable = true;
                    break;
                }
            }

            if (isPrinterAvailable) {

                // connect to printer wifi and show print settings dialog and continue with print flow.
                connectToWifi(mPrinterConfiguration);

                // prints document.
                doPrint();

            } else {
                showWifiListActivity(Constants.REQUEST_CODE_PRINTER);
            }

        }
    }

    private void showWifiListActivity(int requestCode) {
        Intent iWifi = new Intent(mActivity, WifiListActivity.class);
        mActivity.startActivityForResult(iWifi, requestCode);
    }

    private void connectToWifi(WifiConfiguration mWifiConfiguration) {
        mWifiManager.enableNetwork(mWifiConfiguration.networkId, true);
    }

    public void doPrint() {

        try {
            // it is taking some time to connect to printer.. so i used handler.. and waiting for its status.
            mPrintStartHandler.postDelayed(new Runnable() {
                @Override
                public void run() {

                    mPrintStartHandler.postDelayed(this, TIME_OUT);

                    if (mPrinterConfiguration.status == WifiConfiguration.Status.CURRENT) {
                        if (mWifiManager.getConnectionInfo().getSupplicantState() == SupplicantState.COMPLETED) {

                            if (Util.computePDFPageCount(pdfFile) > 0) {
                                printDocument(pdfFile);
                            } else {

                                AlertDialog.Builder alert = new AlertDialog.Builder(mActivity);

                                alert.setMessage("Can't print, Page count is zero.");

                                alert.setNeutralButton("OK", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int i) {
                                        dialog.dismiss();
                                        switchConnection();
                                    }
                                });

                                alert.show();
                            }
                        }
                        mPrintStartHandler.removeCallbacksAndMessages(null);
                    } else {
                        Toast.makeText(mActivity, "Failed to connect to printer!.", Toast.LENGTH_LONG).show();
                        switchConnection();
                        mPrintStartHandler.removeCallbacksAndMessages(null);
                    }
                }
            }, TIME_OUT);
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(mActivity, "Failed to connect to printer!.", Toast.LENGTH_LONG).show();
            switchConnection();
        }
    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    public void printDocument(File pdfFile) {

        mPrintManager = (PrintManager) mActivity.getSystemService(Context.PRINT_SERVICE);

        String jobName = mActivity.getResources().getString(R.string.app_name) + " Document";

        mCurrentPrintJob = mPrintManager.print(jobName, new PrintServicesAdapter(mActivity, mFragment, pdfFile), null);
    }


    @TargetApi(Build.VERSION_CODES.KITKAT)
    public void completePrintJob() {
        mPrintJobs = mPrintManager.getPrintJobs();

        mPrintCompleteHandler.postDelayed(new Runnable() {
            @Override
            public void run() {

                mPrintCompleteHandler.postDelayed(this, CONNECTION_TIME_OUT);

                if (mCurrentPrintJob.getInfo().getState() == PrintJobInfo.STATE_COMPLETED) {

                    // remove that PrintJob from PrintManager.
                    for (int i = 0; i < mPrintJobs.size(); i++) {
                        if (mPrintJobs.get(i).getId() == mCurrentPrintJob.getId()) {
                            mPrintJobs.remove(i);
                        }
                    }

                    // switching back to previous connection..
                    switchConnection();

                    // stops handler..
                    mPrintCompleteHandler.removeCallbacksAndMessages(null);
                } else if (mCurrentPrintJob.getInfo().getState() == PrintJobInfo.STATE_FAILED) {
                    switchConnection();
                    Toast.makeText(mActivity, "Print Failed!", Toast.LENGTH_LONG).show();
                    mPrintCompleteHandler.removeCallbacksAndMessages(null);
                } else if (mCurrentPrintJob.getInfo().getState() == PrintJobInfo.STATE_CANCELED) {
                    switchConnection();
                    Toast.makeText(mActivity, "Print Cancelled!", Toast.LENGTH_LONG).show();
                    mPrintCompleteHandler.removeCallbacksAndMessages(null);
                }

            }
        }, CONNECTION_TIME_OUT);
    }

    public void switchConnection() {
        try {
            if (!isMobileDataConnection) {

                mOldWifiConfiguration = Util.getWifiConfiguration(mActivity, Constants.CONTROLLER_WIFI);

                // get list of wifi available. if wifi configuration available then connect it.
                // else.. show list of available wifi nearby.
                boolean isWifiAvailable = false;

                // scans nearby wifi.
                mWifiManager.startScan();
                setScanResults(mWifiScanner.getScanResults());

                // checks this wifi in scan result list.
                for (int i = 0; i < mScanResults.size(); i++) {
                    if (mOldWifiConfiguration.SSID.equals("\"" + mScanResults.get(i).SSID + "\"")) {
                        isWifiAvailable = true;
                        break;
                    }
                }

                if (isWifiAvailable) {

                    // connect to printer wifi and show print settings dialog and continue with print flow.
                    connectToWifi(mOldWifiConfiguration);

                    mWifiConnectHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mWifiConnectHandler.postDelayed(this, TIME_OUT);
                            if (mOldWifiConfiguration.status == WifiConfiguration.Status.CURRENT) {
                                if (mWifiManager.getConnectionInfo().getSupplicantState() == SupplicantState.COMPLETED) {

                                    try {
                                        mObservable.notifyObserver(true);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }

                                    mWifiConnectHandler.removeCallbacksAndMessages(null);
                                }
                            }
                        }
                    }, TIME_OUT);

                } else {
                    showWifiListActivity(Constants.REQUEST_CODE_WIFI);
                }
            } else {
                mWifiManager.setWifiEnabled(false);
                mObservable.notifyObserver(true);
            }
        } catch (Exception e) {
            mObservable.notifyObserver(true);
            e.printStackTrace();
        }
    }

    public void getPrinterConfigAndPrint() {
        mPrinterConfiguration = Util.getWifiConfiguration(mActivity, Constants.CONTROLLER_PRINTER);
        doPrint();
    }

    public void setScanResults(List<ScanResult> scanResults) {
        this.mScanResults = scanResults;
    }

    public void onPrintCancelled() {
        switchConnection();
    }

    @Override
    public void update() {
        mObservable.detach(this);
    }

    @Override
    public void updateObserver(boolean bool) {

    }

    @Override
    public void updateObserverProgress(int percentage) {

    }

}

With the help of following links I have created this.

If you want to print your file just call print(file)

If you want to download a file and print that,
call downloadAndPrint(fileUrl, fileName)

放低过去 2024-10-18 09:05:59

我唯一能够集成的打印是 Bixolon SPP-R200。他们有一个不错的 SDK,而且很容易找到。我正在寻找 8 1/2 x 11 蓝牙功能,但目前类似的 sdk 似乎是一个相当艰巨的任务

The only printing i have been able to integrate is for the Bixolon SPP-R200. They have a decent SDK available and is pretty easy to find. I'm looking for 8 1/2 x 11 bluetooth capabilities but an sdk for something like that seems to be a pretty tall order right now

辞取 2024-10-18 09:05:59

Star Micronics 有一个用于通过蓝牙(以及 WiFi/以太网和 USB)进行 Android 打印的 SDK。您可以在这里下载:http://www.starmicronics.com/support/SDKDocumentation.aspx。

如上所述,您目前无法进行本机打印,因此您的选择是特定的打印机 API 或第 3 方打印应用程序。

根据我的经验,最好使用 API 而不是外部应用程序。最大的原因是您可以完全控制打印机的行为。如果 API 是智能构建的,则很容易实现。使用第 3 方应用程序有限制,因为您无法按照您想要的方式自定义打印输出。

我链接到的 Star SDK 有一个非常好的示例应用程序,可让您测试和自定义许多打印机功能以查看它们的实际情况。每个函数都记录在源代码中。命令及其参数也可以在应用程序本身中作为屏幕上的快速参考,非常方便。最重要的是,它有详细的记录。

如果选择这种方式,您可以将纯文本与命令一起发送到打印机。 API 负责将数据转换为打印机可以理解的内容。

Star Micronics has an SDK for Android printing via Bluetooth (as well as wifi/ethernet and USB). You can download it here: http://www.starmicronics.com/support/SDKDocumentation.aspx.

As mentioned above, you can't print natively at this point in time so your options are either a specific printer API or a 3rd party printing app.

In my experience, it's best to use an API and not an external application. The biggest reason is you get total control over printer behavior. It's easy to implement if the API is built intelligently. Using an 3rd party app is limiting because you can't customize your print outs the way you want to.

The Star SDK I linked you to has a really nice sample app that lets you test and customize a lot of printer functions to see them in action. Each function is documented in the source code. The commands and their parameters are also available in the app itself as a quick on screen reference which is convenient. On top of all that, it's well documented.

If you choose this way, you can send plain text to the printer along with commands. The API handles converting the data into what the printer can understand.

暖伴 2024-10-18 09:05:59

还有另一个适用于 Android 的打印 SDK,称为 APF。它基于 CUPS,因此支持多达数千台打印机。网站:isb-vietnam.com

There is another printing SDK for Android called APF. It is based on CUPS so up to thousands of printers supported. Website: isb-vietnam.com

故事与诗 2024-10-18 09:05:59

Zebra Technologies 还提供 SDK安卓。我已经尝试过他们的 SDK 和 Bixolon 的(通过写信给 [email protected])。两者都可以正常工作,但如果您更喜欢使用页面描述语言来定义您的文档,您可能会更好关闭使用 Zebra 打印机。

Zebra Technologies also provides an SDK for Android. I have tried both their SDK and Bixolon's (got it by writing to [email protected]). Both work fine, but if you prefer using a page description language to define your documents you are probably better off using a Zebra printer.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文