120 lines
3.8 KiB
C#
120 lines
3.8 KiB
C#
using System;
|
|
using System.IO;
|
|
using UnityEngine;
|
|
using ZFramework.Runtime;
|
|
|
|
namespace HK
|
|
{
|
|
public abstract class HanYin_Android : MonoBehaviour
|
|
{
|
|
[SerializeField] string printer_ip = "192.168.0.126";
|
|
|
|
public virtual void Print(bool isPrintTest = false, params object[] args)
|
|
{
|
|
// 这里面编写实际打印所需的内容,此内容必须同步到实际的类里面进行编写
|
|
// 如:打印一段文本、一个图片等等
|
|
// using (AndroidJavaClass printClass = new AndroidJavaClass("print.Print"))
|
|
// {
|
|
// }
|
|
|
|
// 此内容为案例
|
|
if (isPrintTest)
|
|
PrintTest();
|
|
}
|
|
|
|
void PrintTest()
|
|
{
|
|
try
|
|
{
|
|
PortOpen();
|
|
|
|
using (AndroidJavaClass printClass = new AndroidJavaClass("print.Print"))
|
|
{
|
|
this.printClass = printClass;
|
|
printClass.CallStatic<int>("PrintText", " \n", 1, 1, 0);
|
|
for (int i = 0; i < 3; i++)
|
|
{
|
|
PrintText( "这是一段测试内容");
|
|
PrintNewLine();
|
|
}
|
|
PrintLine();
|
|
CutPaper();
|
|
PortClose();
|
|
}
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
Log.Debug(e);
|
|
throw;
|
|
}
|
|
}
|
|
|
|
protected int PortOpen()
|
|
{
|
|
// 获取UnityPlayer类
|
|
using (AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
|
|
using (AndroidJavaObject currentActivity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity"))
|
|
{
|
|
// Call Print.PortOpen(Context, String)
|
|
using (AndroidJavaClass printClass = new AndroidJavaClass("print.Print"))
|
|
{
|
|
printClass.SetStatic<string>("LanguageEncode", "GB2312");
|
|
string port = $"WiFi,{printer_ip},9100"; // Change to your printer's connection type
|
|
int result = printClass.CallStatic<int>("PortOpen", currentActivity, port);
|
|
Debug.Log($"connect result: {result}");
|
|
return result;
|
|
}
|
|
}
|
|
}
|
|
|
|
public int PrintImage(Texture2D texture)
|
|
{
|
|
using (AndroidJavaClass wrapperClass = new AndroidJavaClass("PrinterWrapper"))
|
|
{
|
|
// Call PrintImage(String path, byte var1, byte var2, int var3)
|
|
byte[] array = texture.EncodeToPNG();
|
|
int result = wrapperClass.Call<int>("PrintImageFromString", array, 0, 0);
|
|
|
|
Debug.Log(result != -1 ? "Print logo success" : "Print logo failed");
|
|
return result;
|
|
}
|
|
}
|
|
|
|
private AndroidJavaClass printClass;
|
|
|
|
public void PrintText(string s, int a = 0, int b = 0, int c = 0)
|
|
{
|
|
printClass.CallStatic<int>("PrintText", s, a, b, c);
|
|
}
|
|
|
|
public void PrintLine()
|
|
{
|
|
printClass.CallStatic<int>("PrintText", " ", 0, 4, 0);
|
|
}
|
|
|
|
public void PrintNewLine()
|
|
{
|
|
printClass.CallStatic<int>("PrintAndLineFeed");
|
|
}
|
|
|
|
public void CutPaper()
|
|
{
|
|
printClass.CallStatic<int>("CutPaper", 1);
|
|
}
|
|
|
|
public void PortClose()
|
|
{
|
|
printClass.CallStatic<bool>("PortClose");
|
|
}
|
|
|
|
private string GetTime()
|
|
{
|
|
string time = DateTime.Now.ToString("h:mm");
|
|
if (DateTime.Now.Hour < 12)
|
|
time += "am";
|
|
else
|
|
time += "pm";
|
|
return time;
|
|
}
|
|
}
|
|
} |