简体   繁体   中英

Advice needed for android phonegap custom plugin

I have developed an app in phonegap (html5, JQuery, JS) and I want to develop a plugin to print to a BT printer.

I download printer manufacturer's SDK and I imported the appropriate .jar file to my project with all the methods I will need in my project.

I create the below plugin, following an internet tutorial, in order to call from JS the JAVA methods from printer manufacturers SDK.

JS

var HelloPlugin = {
    callNativeFunction: function (success, fail, resultType) {
        return cordova.exec(success, fail, "com.tricedesigns.HelloPlugin", "nativeAction", [resultType]);
    }
};

JAVA

package com.tricedesigns;
import org.apache.cordova.api.Plugin;
import org.apache.cordova.api.PluginResult;
import org.json.JSONArray;
import com.starmicronics.stario.StarIOPort;
import com.starmicronics.stario.StarIOPortException;
import com.starmicronics.stario.StarPrinterStatus;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.util.Log;

public class HelloPlugin extends Plugin {

    public static final String NATIVE_ACTION_STRING="nativeAction";
    public static final String SUCCESS_PARAMETER="success";

    @Override
    public PluginResult execute(String action, JSONArray data, String callbackId) {

        if (NATIVE_ACTION_STRING.equals(action)) {
            this.ctx.runOnUiThread(new Runnable()
            {
                public void run()
                {
                    String resultType = null;
                    StarIOPort port = null;
                    String message = null;
                    String portName = "bt:";
                    String portSettings = "mini";
                    byte[] texttoprint = new byte[]{0x1b, 0x40, 0x1b,0x74,0x0D,(byte) 0x91,(byte) 0x92,(byte) 0x93,(byte) 0x94,(byte) 0x95,(byte) 0x96,(byte) 0x97,(byte) 0x98,(byte) 0x99,0x0A,0x0A,0x0A,0x0A,0x0A};

                    try 
                    {
                        port = StarIOPort.getPort(portName, portSettings, 10000);

                        try
                        {
                            Thread.sleep(500);
                        }
                        catch(InterruptedException e) {}

                    }
                    catch (StarIOPortException e)
                    {

                        Builder dialog = new AlertDialog.Builder((Context)ctx);
                        dialog.setNegativeButton("Ok", null);
                        AlertDialog alert = dialog.create();
                        alert.setTitle("Failure");
                        alert.setMessage("Failed to connect to printer");
                        alert.show();
                    }
                    finally
                    {
                        if(port != null)
                        {
                            try 
                            {
                                StarIOPort.releasePort(port);
                            } catch (StarIOPortException e) {}
                        }
                    }
            }
            });
        }
     return null;
    }
}

Printer command manual say:

GetPort is what you will be using to “open” the port to the printer. Using one of the valid inputs for portName and portSettings as mentioned previously before this, you can pass your connection string into the StarIO class so that it will correctly set its private variables.

//The following would be an actual usage of getPort:
StarIOPort port = null;
try
{
port = StarIOPort.getPort(portName, portSettings, 10000);
}
catch (StarIOPortException e)
{
//There was an error opening the port
}

StarIOPort is a part of StarIO and this will allow you to create a “port” handle. The above example shows the port being created and set to null then being assigned the actual port hook on the following line that contains getPort. Always use a try, catch when using getPort. If the port cannot be opened because of connection problems, your program will crash unless you use a try, catch like the above example.

Is the above syntax of plugin correct or is there something i missed?

When I run my app always i receive "Failed to connect to printer" even if the printer is on and connected to my device.

try this:

public PluginResult execute(String action, JSONArray data, String callbackId) {
    PluginResult result = null;
    if (PRINT_ACTION.equals(action))
    {
        JSONObject printerStatusJSON = new JSONObject();
        try {
            Boolean prtStatus = false;
            String msg ="Failed to connect to printer";
            String portName = "";
            ArrayList<PortInfo> dvss = PrinterFunctions.getDevices();//BTPortList  = StarIOPort.searchPrinter("BT:");

            if (Looper.myLooper() == null) {
                Looper.prepare();
            }

            for(PortInfo dvs : dvss) {
                Map<String, String> st = PrinterFunctions.CheckStatus(dvs.getPortName(), "mini");//port = StarIOPort.getPort(portName, portSettings, 1000);
                if(st.get("status") == "true") {
                    prtStatus = true;
                    portName = st.get("portName"); 
                    break;
                }
                msg = st.get("message");
            }

            if(!portName.isEmpty()) {
                PrinterFunctions.PrintSomething(portName, data);//MiniPrinterFunctions.PrintSampleReceipt(String portName, JSONArray data);
            }

            printerStatusJSON.put("prtStatus", prtStatus);
            printerStatusJSON.put("message", msg);

            result = new PluginResult(Status.OK, printerStatusJSON);
        } 
        catch (Exception jsonEx) {
            Log.e("YourApplicationName", "Got JSON Exception " + jsonEx.getMessage());
            jsonEx.printStackTrace();
            result = new PluginResult(Status.JSON_EXCEPTION);
        }
    }
    else {
        result = new PluginResult(Status.INVALID_ACTION);
        Log.e(TAG, "Invalid action : " + action);
    }
    return result;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM