【发布时间】:2012-08-16 01:36:45
【问题描述】:
我在 phonegap (html5, JQuery, JS) 中开发了一个应用程序,我想开发一个插件来打印到 BT 打印机。
我下载了打印机制造商的 SDK,并使用我项目中需要的所有方法将相应的 .jar 文件导入到我的项目中。
我根据互联网教程创建了以下插件,以便从 JS 调用打印机制造商 SDK 的 JAVA 方法。
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;
}
}
打印机命令手册说:
GetPort 用于“打开”打印机端口。使用其中一个有效的 如前面提到的 portName 和 portSettings 的输入,您可以通过 连接字符串到 StarIO 类中,以便正确设置其私有变量。
//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 是 StarIO 的一部分,这将允许您创建一个“端口”句柄。这 上面的例子显示了端口被创建并设置为 null 然后被分配实际的 包含 getPort 的以下行上的端口挂钩。 使用 getPort 时始终使用 try, catch。如果端口无法打开 由于连接问题,除非您使用 try, catch 像上面的例子一样。
上面的插件语法是正确的还是我遗漏了什么?
当我运行我的应用程序时,我总是收到“无法连接到打印机”,即使打印机已打开并连接到我的设备。
【问题讨论】:
-
这是开源项目的一部分吗?我想帮忙。
-
你能解释一下你添加 jar 文件的步骤吗?
标签: java android printing phonegap-plugins stario-sdk