master
张萌 3 years ago
parent bc490ff3f8
commit ddd41aaafb

@ -1,17 +1,25 @@
<component name="libraryTable">
<library name="Dart SDK">
<CLASSES>
<root url="file:///Users/zhangmeng/flutter/bin/cache/dart-sdk/lib/async" />
<root url="file:///Users/zhangmeng/flutter/bin/cache/dart-sdk/lib/collection" />
<root url="file:///Users/zhangmeng/flutter/bin/cache/dart-sdk/lib/convert" />
<root url="file:///Users/zhangmeng/flutter/bin/cache/dart-sdk/lib/core" />
<root url="file:///Users/zhangmeng/flutter/bin/cache/dart-sdk/lib/developer" />
<root url="file:///Users/zhangmeng/flutter/bin/cache/dart-sdk/lib/html" />
<root url="file:///Users/zhangmeng/flutter/bin/cache/dart-sdk/lib/io" />
<root url="file:///Users/zhangmeng/flutter/bin/cache/dart-sdk/lib/isolate" />
<root url="file:///Users/zhangmeng/flutter/bin/cache/dart-sdk/lib/math" />
<root url="file:///Users/zhangmeng/flutter/bin/cache/dart-sdk/lib/mirrors" />
<root url="file:///Users/zhangmeng/flutter/bin/cache/dart-sdk/lib/typed_data" />
<root url="file://$PROJECT_DIR$/../fvm/versions/2.8.1/bin/cache/dart-sdk/lib/async" />
<root url="file://$PROJECT_DIR$/../fvm/versions/2.8.1/bin/cache/dart-sdk/lib/cli" />
<root url="file://$PROJECT_DIR$/../fvm/versions/2.8.1/bin/cache/dart-sdk/lib/collection" />
<root url="file://$PROJECT_DIR$/../fvm/versions/2.8.1/bin/cache/dart-sdk/lib/convert" />
<root url="file://$PROJECT_DIR$/../fvm/versions/2.8.1/bin/cache/dart-sdk/lib/core" />
<root url="file://$PROJECT_DIR$/../fvm/versions/2.8.1/bin/cache/dart-sdk/lib/developer" />
<root url="file://$PROJECT_DIR$/../fvm/versions/2.8.1/bin/cache/dart-sdk/lib/ffi" />
<root url="file://$PROJECT_DIR$/../fvm/versions/2.8.1/bin/cache/dart-sdk/lib/html" />
<root url="file://$PROJECT_DIR$/../fvm/versions/2.8.1/bin/cache/dart-sdk/lib/indexed_db" />
<root url="file://$PROJECT_DIR$/../fvm/versions/2.8.1/bin/cache/dart-sdk/lib/io" />
<root url="file://$PROJECT_DIR$/../fvm/versions/2.8.1/bin/cache/dart-sdk/lib/isolate" />
<root url="file://$PROJECT_DIR$/../fvm/versions/2.8.1/bin/cache/dart-sdk/lib/js" />
<root url="file://$PROJECT_DIR$/../fvm/versions/2.8.1/bin/cache/dart-sdk/lib/js_util" />
<root url="file://$PROJECT_DIR$/../fvm/versions/2.8.1/bin/cache/dart-sdk/lib/math" />
<root url="file://$PROJECT_DIR$/../fvm/versions/2.8.1/bin/cache/dart-sdk/lib/mirrors" />
<root url="file://$PROJECT_DIR$/../fvm/versions/2.8.1/bin/cache/dart-sdk/lib/svg" />
<root url="file://$PROJECT_DIR$/../fvm/versions/2.8.1/bin/cache/dart-sdk/lib/typed_data" />
<root url="file://$PROJECT_DIR$/../fvm/versions/2.8.1/bin/cache/dart-sdk/lib/web_audio" />
<root url="file://$PROJECT_DIR$/../fvm/versions/2.8.1/bin/cache/dart-sdk/lib/web_gl" />
</CLASSES>
<JAVADOC />
<SOURCES />

@ -0,0 +1,9 @@
<component name="libraryTable">
<library name="Flutter Plugins" type="FlutterPluginsLibraryType">
<CLASSES>
<root url="file://$PROJECT_DIR$" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</component>

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="Android API 28 Platform" project-jdk-type="Android SDK" />
</project>

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>

@ -1,45 +1,107 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="FileEditorManager">
<leaf>
<file leaf-file-name="dj_printer.dart" pinned="false" current-in-tab="true">
<entry file="file://$PROJECT_DIR$/lib/dj_printer.dart">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="0">
<caret line="0" column="0" lean-forward="false" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
</state>
</provider>
</entry>
</file>
<file leaf-file-name="main.dart" pinned="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/example/lib/main.dart">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="0">
<caret line="0" column="0" lean-forward="false" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
</state>
</provider>
</entry>
</file>
</leaf>
<component name="ChangeListManager">
<list default="true" id="2f8e3712-04e2-429a-bcea-c8db1a54008e" name="默认变更列表" comment="">
<change afterPath="$PROJECT_DIR$/android/libs/Sewoo_Android_1109.jar" afterDir="false" />
<change afterPath="$PROJECT_DIR$/android/src/main/java/com/dj/printer/dj_printer/AsPrint.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/android/src/main/java/com/dj/printer/dj_printer/Blutooth.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/lib/src/device_model.dart" afterDir="false" />
<change afterPath="$PROJECT_DIR$/lib/src/status_enum.dart" afterDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/libraries/Dart_SDK.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/libraries/Dart_SDK.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/android/build.gradle" beforeDir="false" afterPath="$PROJECT_DIR$/android/build.gradle" afterDir="false" />
<change beforePath="$PROJECT_DIR$/android/src/main/AndroidManifest.xml" beforeDir="false" afterPath="$PROJECT_DIR$/android/src/main/AndroidManifest.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/android/src/main/java/com/dj/printer/dj_printer/DjPrinterPlugin.java" beforeDir="false" afterPath="$PROJECT_DIR$/android/src/main/java/com/dj/printer/dj_printer/DjPrinterPlugin.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/dj_printer.iml" beforeDir="false" afterPath="$PROJECT_DIR$/dj_printer.iml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/example/android/app/build.gradle" beforeDir="false" afterPath="$PROJECT_DIR$/example/android/app/build.gradle" afterDir="false" />
<change beforePath="$PROJECT_DIR$/example/android/app/src/main/AndroidManifest.xml" beforeDir="false" afterPath="$PROJECT_DIR$/example/android/app/src/main/AndroidManifest.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/example/lib/main.dart" beforeDir="false" afterPath="$PROJECT_DIR$/example/lib/main.dart" afterDir="false" />
<change beforePath="$PROJECT_DIR$/example/pubspec.lock" beforeDir="false" afterPath="$PROJECT_DIR$/example/pubspec.lock" afterDir="false" />
<change beforePath="$PROJECT_DIR$/example/pubspec.yaml" beforeDir="false" afterPath="$PROJECT_DIR$/example/pubspec.yaml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/lib/dj_printer.dart" beforeDir="false" afterPath="$PROJECT_DIR$/lib/dj_printer.dart" afterDir="false" />
<change beforePath="$PROJECT_DIR$/pubspec.lock" beforeDir="false" afterPath="$PROJECT_DIR$/pubspec.lock" afterDir="false" />
<change beforePath="$PROJECT_DIR$/test/dj_printer_test.dart" beforeDir="false" afterPath="$PROJECT_DIR$/test/dj_printer_test.dart" afterDir="false" />
</list>
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
<option name="LAST_RESOLUTION" value="IGNORE" />
</component>
<component name="ToolWindowManager">
<editor active="true" />
<layout>
<window_info id="Project" active="true" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="0" side_tool="false" content_ui="combo" />
</layout>
<component name="FileTemplateManagerImpl">
<option name="RECENT_TEMPLATES">
<list>
<option value="Dart File" />
</list>
</option>
</component>
<component name="Git.Settings">
<option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
</component>
<component name="GitSEFilterConfiguration">
<file-type-list>
<filtered-out-file-type name="LOCAL_BRANCH" />
<filtered-out-file-type name="REMOTE_BRANCH" />
<filtered-out-file-type name="TAG" />
<filtered-out-file-type name="COMMIT_BY_MESSAGE" />
</file-type-list>
</component>
<component name="HighlightingSettingsPerFile">
<setting file="file://$PROJECT_DIR$/example/pubspec.yaml" root0="SKIP_INSPECTION" />
<setting file="file://$PROJECT_DIR$/lib/dj_printer.dart" root0="SKIP_INSPECTION" />
<setting file="file://$PROJECT_DIR$/example/lib/main.dart" root0="SKIP_INSPECTION" />
</component>
<component name="ProjectId" id="20i7PcthqmcXBmYTwGkZSh1utIA" />
<component name="ProjectView">
<navigator currentView="ProjectPane" proportions="" version="1">
</navigator>
<navigator currentView="ProjectPane" proportions="" version="1" />
<panes>
<pane id="ProjectPane">
<option name="show-excluded-files" value="false" />
</pane>
</panes>
</component>
<component name="ProjectViewState">
<option name="hideEmptyMiddlePackages" value="true" />
<option name="showLibraryContents" value="true" />
</component>
<component name="PropertiesComponent">
<property name="last_opened_file_path" value="$PROJECT_DIR$" />
<property name="dart.analysis.tool.window.force.activate" value="true" />
<property name="dart.analysis.tool.window.visible" value="false" />
<property name="io.flutter.reload.alreadyRun" value="true" />
<property name="last_opened_file_path" value="$PROJECT_DIR$" />
<property name="settings.editor.selected.configurable" value="flutter.settings" />
<property name="show.migrate.to.gradle.popup" value="false" />
</component>
<component name="SpellCheckerSettings" RuntimeDictionaries="0" Folders="0" CustomDictionaries="0" DefaultDictionary="应用程序级" UseSingleDictionary="true" transferred="true" />
<component name="TaskManager">
<task active="true" id="Default" summary="默认任务">
<changelist id="2f8e3712-04e2-429a-bcea-c8db1a54008e" name="默认变更列表" comment="" />
<created>1636515532083</created>
<option name="number" value="Default" />
<option name="presentableId" value="Default" />
<updated>1636515532083</updated>
</task>
<servers />
</component>
<component name="ToolWindowManager">
<editor active="true" />
<layout>
<window_info id="Project" active="true" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="0" side_tool="false" content_ui="combo" />
</layout>
</component>
<component name="Vcs.Log.Tabs.Properties">
<option name="TAB_STATES">
<map>
<entry key="MAIN">
<value>
<State />
</value>
</entry>
</map>
</option>
<option name="oldMeFiltersMigrated" value="true" />
</component>
<component name="XSLT-Support.FileAssociations.UIState">
<expand />
<select />
</component>
</project>

@ -0,0 +1,3 @@
# Default ignored files
/shelf/
/workspace.xml

@ -0,0 +1 @@
dj_printer

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<bytecodeTargetLevel target="11" />
</component>
</project>

@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GradleMigrationSettings" migrationVersion="1" />
<component name="GradleSettings">
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="testRunner" value="GRADLE" />
<option name="distributionType" value="DEFAULT_WRAPPED" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="modules">
<set>
<option value="$PROJECT_DIR$" />
</set>
</option>
<option name="resolveModulePerSourceSet" value="false" />
</GradleProjectSettings>
</option>
</component>
</project>

@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="RemoteRepositoriesConfiguration">
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Maven Central repository" />
<option name="url" value="https://repo1.maven.org/maven2" />
</remote-repository>
<remote-repository>
<option name="id" value="jboss.community" />
<option name="name" value="JBoss Community repository" />
<option name="url" value="https://repository.jboss.org/nexus/content/repositories/public/" />
</remote-repository>
<remote-repository>
<option name="id" value="MavenRepo" />
<option name="name" value="MavenRepo" />
<option name="url" value="https://repo.maven.apache.org/maven2/" />
</remote-repository>
<remote-repository>
<option name="id" value="Google" />
<option name="name" value="Google" />
<option name="url" value="https://dl.google.com/dl/android/maven2/" />
</remote-repository>
</component>
</project>

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" languageLevel="JDK_11" default="true" project-jdk-name="11" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/build/classes" />
</component>
<component name="ProjectType">
<option name="id" value="Android" />
</component>
</project>

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/modules/dj_printer.iml" filepath="$PROJECT_DIR$/.idea/modules/dj_printer.iml" />
</modules>
</component>
</project>

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$/.." vcs="Git" />
</component>
</project>

@ -33,3 +33,8 @@ android {
minSdkVersion 16
}
}
dependencies {
implementation fileTree(dir: "libs",includes: ["*.jar"])
implementation files('libs/Sewoo_Android_1109.jar')
}

@ -1,3 +1,8 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.dj.printer.dj_printer">
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
</manifest>

@ -0,0 +1,67 @@
package com.dj.printer.dj_printer;
import android.graphics.Typeface;
import com.sewoo.jpos.command.CPCLConst;
import com.sewoo.jpos.printer.CPCLPrinter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
public class AsPrint {
private CPCLPrinter cpclPrinter;
public AsPrint() {
System.out.println("cpcl初始化");
// cpclPrinter = new CPCLPrinter(); //Default = English.
//cpclPrinter = new CPCLPrinter("EUC-KR"); // Korean.
cpclPrinter = new CPCLPrinter("GB2312"); //Chinese.
cpclPrinter.setMeasure(CPCLConst.LK_CPCL_MILLI);
}
public void printAsCode(String code, String channel, String country, String countStr, int offset, boolean hasPlan) throws IOException {
if (hasPlan) {
PrintPlan(code, channel, country, countStr, offset);
} else {
PrintNoPlan(code, countStr, offset);
}
}
private void PrintPlan(String code, String channel, String country, String countStr, int offset) throws IOException {
//2-inch
cpclPrinter.setForm(0, 203, 203, 500, 575, 0, 1);
cpclPrinter.setMedia(CPCLConst.LK_CPCL_LABEL);
cpclPrinter.setJustification(CPCLConst.LK_CPCL_CENTER);
cpclPrinter.setCPCLBarcode(0, 0, 0);
cpclPrinter.printCPCLBarcode(CPCLConst.LK_CPCL_0_ROTATION, CPCLConst.LK_CPCL_BCS_128, 1, CPCLConst.LK_CPCL_BCS_4RATIO, 130, 0, 26, code, 0);
cpclPrinter.printCPCLText(0, 0, 3, 0, 170, code, 0);
cpclPrinter.printLine(0, 220, 535, 220, 3);
cpclPrinter.setJustification(CPCLConst.LK_CPCL_LEFT);
cpclPrinter.printAndroidFont(40, 240, Typeface.DEFAULT_BOLD, true, "渠道名称:", 575, 30);
cpclPrinter.printAndroidFont(170, 240, Typeface.DEFAULT, channel, 575, 30);
cpclPrinter.printAndroidFont(40, 300, Typeface.DEFAULT, "目的地:" + country, 575, 30);
cpclPrinter.printAndroidFont(400 - offset, 300, Typeface.DEFAULT_BOLD, true, "件数:", 575, 30);
cpclPrinter.printAndroidFont(480 - offset, 300, Typeface.DEFAULT, countStr, 575, 30);
cpclPrinter.printForm();
}
private void PrintNoPlan(String code, String countStr, int offset) throws IOException {
//2-inch
cpclPrinter.setForm(0, 203, 203, 500, 575, 0, 1);
cpclPrinter.setMedia(CPCLConst.LK_CPCL_LABEL);
cpclPrinter.setJustification(CPCLConst.LK_CPCL_CENTER);
cpclPrinter.setCPCLBarcode(0, 0, 0);
cpclPrinter.printCPCLBarcode(CPCLConst.LK_CPCL_0_ROTATION, CPCLConst.LK_CPCL_BCS_128, 1, CPCLConst.LK_CPCL_BCS_4RATIO, 130, 0, 26, code, 0);
cpclPrinter.printCPCLText(0, 0, 3, 0, 170, code, 0);
cpclPrinter.printLine(0, 220, 535, 220, 3);
cpclPrinter.setJustification(CPCLConst.LK_CPCL_LEFT);
cpclPrinter.printAndroidFont(40, 240, Typeface.DEFAULT_BOLD, true, "未建计划", 575, 50);
cpclPrinter.printAndroidFont(400, 240, Typeface.DEFAULT_BOLD, true, "件数:", 575, 50);
cpclPrinter.printAndroidFont(400 - offset, 300, Typeface.DEFAULT, countStr, 575, 30);
cpclPrinter.printForm();
}
public int Get_Status() {
return cpclPrinter.status();
}
}

@ -0,0 +1,306 @@
package com.dj.printer.dj_printer;
import android.Manifest;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import com.sewoo.port.android.BluetoothPort;
import com.sewoo.request.android.RequestHandler;
import java.io.IOException;
import io.flutter.plugin.common.EventChannel;
public class Blutooth {
private BluetoothAdapter mBluetoothAdapter;
private BluetoothPort bluetoothPort;
private BroadcastReceiver connectDevice;
private BroadcastReceiver discoveryResult;
private BroadcastReceiver searchFinish;
private BroadcastReceiver searchStart;
private Thread btThread;
private boolean searchflags;
private boolean disconnectflags;
public void init() {
bluetoothPort = BluetoothPort.getInstance();
bluetoothPort.SetMacFilter(false);
bluetoothSetup();
searchflags = false;
disconnectflags=false;
System.out.println("初始化完成");
}
//初始化连接监听
public void createConnectBroadcast(Context context, EventChannel.EventSink eventSink) {
connectDevice = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
eventSink.success("connected");
} else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
try {
if (bluetoothPort.isConnected()) {
bluetoothPort.disconnect();
if ((btThread != null) && (btThread.isAlive())) {
cancelThread();
}
eventSink.success("disconnected");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
context.registerReceiver(connectDevice, new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED));
context.registerReceiver(connectDevice, new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED));
System.out.println("注册连接广播");
}
//初始化搜索设备监听
public void createDiscoveryBroadcast(Context context, EventChannel.EventSink eventSink) {
discoveryResult = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String key = "";
BluetoothDevice remoteDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String name = remoteDevice.getName();
if (remoteDevice != null && name != null) {
if (remoteDevice.getBondState() != BluetoothDevice.BOND_BONDED) {
key = "{" + "\"name\":" + "\"" + name + "\"" + ","
+ "\"address\":" + "\"" + remoteDevice.getAddress() + "\"" + ","
+ "\"isPaired\":" + false
+ "}";
} else {
key = "{" + "\"name\":" + "\"" + name + "\"" + ","
+ "\"address\":" + "\"" + remoteDevice.getAddress() + "\"" + ","
+ "\"isPaired\":" + true
+ "}";
}
if (bluetoothPort.isValidAddress(remoteDevice.getAddress())) {
eventSink.success(key);
System.out.println(key);
}
}
}
};
context.registerReceiver(discoveryResult, new IntentFilter(BluetoothDevice.ACTION_FOUND));
searchStart = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
eventSink.success("start");
System.out.println("start");
}
};
context.registerReceiver(searchStart, new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED));
searchFinish = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
eventSink.success("finish");
searchflags = true;
System.out.println("finish");
}
};
context.registerReceiver(searchFinish, new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED));
System.out.println("注册搜索广播");
}
//蓝牙设置
private void bluetoothSetup() {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
System.out.println("不支持蓝牙");
}
}
//搜索设备
public void SearchingBTDevice() {
new CheckTypesTask().execute();
System.out.println("开始搜索");
}
public void btConn(final String address) throws IOException {
// bluetoothPort.connect(address);
new connBT().execute(address);
}
//断开连接
public void DisconnectDevice(Context context) {
try {
bluetoothPort.disconnect();
if((btThread != null) && (btThread.isAlive()))
btThread.interrupt();
disconnectflags = true;
context.unregisterReceiver(connectDevice);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//取消搜索
public void cancelDiscoveryResult(Context context) {
mBluetoothAdapter.cancelDiscovery();
context.unregisterReceiver(discoveryResult);
}
public void cancelThread() {
btThread.interrupt();
btThread = null;
}
private class CheckTypesTask extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
mBluetoothAdapter.startDiscovery();
super.onPreExecute();
}
;
@Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
while (true) {
if (searchflags)
break;
Thread.sleep(100);
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
searchflags = false;
super.onPostExecute(result);
}
;
}
class connBT extends AsyncTask<String, Void, Integer> {
@Override
protected Integer doInBackground(String... strings) {
Integer retVal = null;
try {
bluetoothPort.connect(strings[0]);
retVal = Integer.valueOf(0);
} catch (IOException e) {
e.printStackTrace();
retVal = Integer.valueOf(-1);
}
return retVal;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onPostExecute(Integer result) {
if (result.intValue() == 0) // Connection success.
{
RequestHandler rh = new RequestHandler();
btThread = new Thread(rh);
btThread.start();
} else // Connection failed.
{
}
super.onPostExecute(result);
}
}
public void ExcuteDisconnect(Context context)
{
new ExcuteDisconnectBT().execute(context);
}
private class ExcuteDisconnectBT extends AsyncTask<Context, Void, Void>{
@Override
protected Void doInBackground(Context... contexts) {
try {
DisconnectDevice(contexts[0]);
while(true)
{
if(disconnectflags)
break;
Thread.sleep(100);
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
protected void onPreExecute(){
super.onPreExecute();
};
@Override
protected void onPostExecute(Void result){
disconnectflags = false;
super.onPostExecute(result);
};
}
}

@ -1,31 +1,104 @@
package com.dj.printer.dj_printer;
import android.content.Context;
import androidx.annotation.NonNull;
import com.sewoo.jpos.command.CPCLConst;
import com.sewoo.jpos.printer.CPCLPrinter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.plugin.common.EventChannel;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
/** DjPrinterPlugin */
/**
* DjPrinterPlugin
*/
public class DjPrinterPlugin implements FlutterPlugin, MethodCallHandler {
/// The MethodChannel that will the communication between Flutter and native Android
///
/// This local reference serves to register the plugin with the Flutter Engine and unregister it
/// when the Flutter Engine is detached from the Activity
private MethodChannel channel;
private EventChannel discoveryChannel;
private EventChannel connectChannel;
private Context context;
AsPrint asPrint;
private static final String DISCOVERYDEVICE = "com.discovery.devices";
private static final String CONNECT = "com.connect";
Blutooth blutooth = new Blutooth();
@Override
public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "dj_printer");
channel.setMethodCallHandler(this);
context = flutterPluginBinding.getApplicationContext();
discoveryChannel = new EventChannel(flutterPluginBinding.getBinaryMessenger(), DISCOVERYDEVICE);
connectChannel = new EventChannel(flutterPluginBinding.getBinaryMessenger(), CONNECT);
discoveryChannel.setStreamHandler(new EventChannel.StreamHandler() {
@Override
public void onListen(Object arguments, EventChannel.EventSink events) {
blutooth.createDiscoveryBroadcast(context, events);
}
@Override
public void onCancel(Object arguments) {
blutooth.cancelDiscoveryResult(context);
}
});
connectChannel.setStreamHandler(new EventChannel.StreamHandler() {
@Override
public void onListen(Object arguments, EventChannel.EventSink events) {
blutooth.createConnectBroadcast(context, events);
}
@Override
public void onCancel(Object arguments) {
blutooth.ExcuteDisconnect(context);
}
});
}
@Override
public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
if (call.method.equals("getPlatformVersion")) {
result.success("Android " + android.os.Build.VERSION.RELEASE);
if (call.method.equals("startSearch")) {
blutooth.SearchingBTDevice();
} else if (call.method.equals("connect")) {
String arg = call.argument("address");
try {
blutooth.btConn(arg);
result.success(true);
} catch (IOException e) {
e.printStackTrace();
}
} else if (call.method.equals("init")) {
blutooth.init();
asPrint = new AsPrint();
result.success(true);
} else if (call.method.equals("print")) {
try {
String code = call.argument("code");
String channel = call.argument("channel");
String country = call.argument("country");
String countStr = call.argument("countStr");
int offset = call.argument("offset");
boolean hasPlan = call.argument("hasPlan");
asPrint.printAsCode(code, channel, country, countStr, offset, hasPlan);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
result.success(true);
} else if (call.method.equals("getStatus")) {
int sta = asPrint.Get_Status();
result.success(sta);
} else {
result.notImplemented();
}
@ -35,4 +108,5 @@ public class DjPrinterPlugin implements FlutterPlugin, MethodCallHandler {
public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
channel.setMethodCallHandler(null);
}
}

@ -8,11 +8,11 @@
<excludeFolder url="file://$MODULE_DIR$/.idea" />
<excludeFolder url="file://$MODULE_DIR$/.pub" />
<excludeFolder url="file://$MODULE_DIR$/build" />
<excludeFolder url="file://$MODULE_DIR$/example/.pub" />
<excludeFolder url="file://$MODULE_DIR$/example/build" />
<excludeFolder url="file://$MODULE_DIR$/example/.dart_tool" />
<excludeFolder url="file://$MODULE_DIR$/example/.pub" />
</content>
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="Dart Packages" level="project" />
<orderEntry type="library" name="Dart SDK" level="project" />
<orderEntry type="library" name="Flutter Plugins" level="project" />
</component>

@ -25,7 +25,7 @@ apply plugin: 'com.android.application'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
android {
compileSdkVersion 30
compileSdkVersion 31
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
@ -48,6 +48,11 @@ android {
signingConfig signingConfigs.debug
}
}
packagingOptions {
exclude "META-INF/DEPENDENCIES"
}
}
flutter {

@ -38,4 +38,8 @@
android:name="flutterEmbedding"
android:value="2" />
</application>
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
</manifest>

@ -1,8 +1,10 @@
import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:convert';
import 'package:flutter/services.dart';
import 'package:dj_printer/dj_printer.dart';
import 'package:dj_printer/src/device_model.dart';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
void main() {
runApp(const MyApp());
@ -16,7 +18,7 @@ class MyApp extends StatefulWidget {
}
class _MyAppState extends State<MyApp> {
String _platformVersion = 'Unknown';
List<Device> devices = [];
@override
void initState() {
@ -26,23 +28,30 @@ class _MyAppState extends State<MyApp> {
// Platform messages are asynchronous, so we initialize in an async method.
Future<void> initPlatformState() async {
String platformVersion;
// Platform messages may fail, so we use a try/catch PlatformException.
// We also handle the message potentially returning null.
try {
platformVersion =
await DjPrinter.platformVersion ?? 'Unknown platform version';
} on PlatformException {
platformVersion = 'Failed to get platform version.';
}
// If the widget was removed from the tree while the asynchronous platform
// message was in flight, we want to discard the reply rather than calling
// setState to update our non-existent appearance.
if (!mounted) return;
setState(() {
_platformVersion = platformVersion;
var per = await Permission.bluetooth.isGranted;
if (!per) {
Permission.bluetooth.request();
}
var pers = await Permission.locationWhenInUse.isGranted;
if (!pers) {
Permission.locationWhenInUse.request();
}
DjPrinter.init();
DjPrinter.addDiscoveryListen(onReceive: (data) {
var js = json.decode(data.toString());
devices.add(Device(
name: js['name'], address: js['address'], isPaired: js['isPaired']));
setState(() {});
}, onStart: () {
print("————————————————————————");
}, onFinish: () {
print('——————————————————————————————');
DjPrinter.cancelDiscovery();
});
DjPrinter.addConnectListen(onConnect: () {
print("connected");
}, onDisconnect: () {
print('disconnected');
});
}
@ -54,7 +63,41 @@ class _MyAppState extends State<MyApp> {
title: const Text('Plugin example app'),
),
body: Center(
child: Text('Running on: $_platformVersion\n'),
child: Column(
children: [
TextButton(
onPressed: () {
devices.clear();
DjPrinter.startSearch;
},
child: const Text('扫描设备')),
// TextButton(onPressed: () {}, child: const Text('打印')),
const SizedBox(
height: 20,
),
...devices
.map((e) => TextButton(
onPressed: () {
DjPrinter.connect(e.address);
},
child: Text(e.name)))
.toList(),
const SizedBox(
height: 20,
),
TextButton(
onPressed: () {
DjPrinter.print(
code: 'ASSZ2022012500010002',
channel: 'cosco定提-月达-卡派',
country: '美国',
countStr: '10/20',
offset: 0,
hasPlan: false);
},
child: const Text('打印'))
],
),
),
),
);

@ -7,7 +7,7 @@ packages:
name: async
url: "https://pub.flutter-io.cn"
source: hosted
version: "2.7.0"
version: "2.8.2"
boolean_selector:
dependency: transitive
description:
@ -15,13 +15,20 @@ packages:
url: "https://pub.flutter-io.cn"
source: hosted
version: "2.1.0"
bot_toast:
dependency: "direct main"
description:
name: bot_toast
url: "https://pub.flutter-io.cn"
source: hosted
version: "4.0.1"
characters:
dependency: transitive
description:
name: characters
url: "https://pub.flutter-io.cn"
source: hosted
version: "1.1.0"
version: "1.2.0"
charcode:
dependency: transitive
description:
@ -94,14 +101,14 @@ packages:
name: matcher
url: "https://pub.flutter-io.cn"
source: hosted
version: "0.12.10"
version: "0.12.11"
meta:
dependency: transitive
description:
name: meta
url: "https://pub.flutter-io.cn"
source: hosted
version: "1.4.0"
version: "1.7.0"
path:
dependency: transitive
description:
@ -109,6 +116,48 @@ packages:
url: "https://pub.flutter-io.cn"
source: hosted
version: "1.8.0"
permission_handler:
dependency: "direct main"
description:
name: permission_handler
url: "https://pub.flutter-io.cn"
source: hosted
version: "9.2.0"
permission_handler_android:
dependency: transitive
description:
name: permission_handler_android
url: "https://pub.flutter-io.cn"
source: hosted
version: "9.0.2"
permission_handler_apple:
dependency: transitive
description:
name: permission_handler_apple
url: "https://pub.flutter-io.cn"
source: hosted
version: "9.0.2"
permission_handler_platform_interface:
dependency: transitive
description:
name: permission_handler_platform_interface
url: "https://pub.flutter-io.cn"
source: hosted
version: "3.7.0"
permission_handler_windows:
dependency: transitive
description:
name: permission_handler_windows
url: "https://pub.flutter-io.cn"
source: hosted
version: "0.1.0"
plugin_platform_interface:
dependency: transitive
description:
name: plugin_platform_interface
url: "https://pub.flutter-io.cn"
source: hosted
version: "2.1.2"
sky_engine:
dependency: transitive
description: flutter
@ -155,7 +204,7 @@ packages:
name: test_api
url: "https://pub.flutter-io.cn"
source: hosted
version: "0.4.1"
version: "0.4.3"
typed_data:
dependency: transitive
description:
@ -169,7 +218,7 @@ packages:
name: vector_math
url: "https://pub.flutter-io.cn"
source: hosted
version: "2.1.0"
version: "2.1.1"
sdks:
dart: ">=2.12.0 <3.0.0"
flutter: ">=1.20.0"
dart: ">=2.15.0 <3.0.0"
flutter: ">=2.8.0"

@ -17,7 +17,6 @@ environment:
dependencies:
flutter:
sdk: flutter
dj_printer:
# When depending on this package from a real application you should use:
# dj_printer: ^x.y.z
@ -29,6 +28,8 @@ dependencies:
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.2
permission_handler: ^9.2.0
bot_toast: ^4.0.1
dev_dependencies:
flutter_test:

@ -1,13 +1,119 @@
import 'dart:async';
import 'package:dj_printer/src/status_enum.dart';
import 'package:flutter/services.dart';
class DjPrinter {
static const MethodChannel _channel = MethodChannel('dj_printer');
static const EventChannel _deviceChannel =
EventChannel("com.discovery.devices");
static StreamSubscription? _discoveryStream;
static Future<StreamSubscription> addDiscoveryListen(
{required void Function(dynamic data) onReceive,
void Function()? onStart,
void Function()? onFinish}) async {
if (_discoveryStream == null) {
return _deviceChannel.receiveBroadcastStream().listen((data) {
if (data == "start" && onStart != null) {
onStart();
} else if (data == "finish" && onFinish != null) {
onFinish();
} else {
onReceive(data);
}
});
} else {
return _discoveryStream!;
}
}
static void cancelDiscovery() {
if (_discoveryStream != null) {
_discoveryStream!.cancel();
_discoveryStream = null;
}
}
static const EventChannel _connectChannel = EventChannel("com.connect");
static StreamSubscription? _connectStream;
static Future<StreamSubscription> addConnectListen(
{required void Function() onConnect,
required void Function() onDisconnect}) async {
if (_connectStream == null) {
return _connectChannel.receiveBroadcastStream().listen((data) {
if (data == 'connected') {
onConnect();
} else if (data == 'disconnected') {
onDisconnect();
}
});
} else {
return _connectStream!;
}
}
static void cancelConnect() {
if (_connectStream != null) {
_connectStream!.cancel();
_connectStream = null;
}
}
static Future<bool?> get startSearch async {
final res = await _channel.invokeMethod('startSearch');
return res;
}
static Future<bool?> connect(String address) async {
final res = await _channel.invokeMethod('connect', {'address': address});
return res;
}
static Future<bool?> init() async {
final res = await _channel.invokeMethod('init');
return res;
}
//0 normal
//1 busy
//2 paper empty
//4 cover open
//8 battery low
static Future<PRINT_STATUS?> getStatus() async {
final res = await _channel.invokeMethod('getStatus');
switch (res) {
case 0:
return PRINT_STATUS.normal;
case 1:
return PRINT_STATUS.busy;
case 2:
return PRINT_STATUS.paperEmpty;
case 4:
return PRINT_STATUS.coverOpen;
case 8:
return PRINT_STATUS.batteryLow;
default:
return null;
}
}
static Future<String?> get platformVersion async {
final String? version = await _channel.invokeMethod('getPlatformVersion');
return version;
static Future<bool?> print(
{required String code,
required String channel,
required String country,
required String countStr,
required int offset,
required bool hasPlan}) async {
final res = await _channel.invokeMethod('print', {
'code': code,
'channel': channel,
'country': country,
'countStr': countStr,
'offset': offset,
'hasPlan': hasPlan,
});
return res;
}
}

@ -0,0 +1,11 @@
class Device {
String name;
String address;
bool isPaired;
Device({
required this.name,
required this.address,
required this.isPaired,
});
}

@ -0,0 +1,7 @@
enum PRINT_STATUS {
normal,
busy,
paperEmpty,
coverOpen,
batteryLow,
}

@ -7,7 +7,7 @@ packages:
name: async
url: "https://pub.flutter-io.cn"
source: hosted
version: "2.7.0"
version: "2.8.2"
boolean_selector:
dependency: transitive
description:
@ -21,7 +21,7 @@ packages:
name: characters
url: "https://pub.flutter-io.cn"
source: hosted
version: "1.1.0"
version: "1.2.0"
charcode:
dependency: transitive
description:
@ -80,14 +80,14 @@ packages:
name: matcher
url: "https://pub.flutter-io.cn"
source: hosted
version: "0.12.10"
version: "0.12.11"
meta:
dependency: transitive
description:
name: meta
url: "https://pub.flutter-io.cn"
source: hosted
version: "1.4.0"
version: "1.7.0"
path:
dependency: transitive
description:
@ -141,7 +141,7 @@ packages:
name: test_api
url: "https://pub.flutter-io.cn"
source: hosted
version: "0.4.1"
version: "0.4.3"
typed_data:
dependency: transitive
description:
@ -155,7 +155,7 @@ packages:
name: vector_math
url: "https://pub.flutter-io.cn"
source: hosted
version: "2.1.0"
version: "2.1.1"
sdks:
dart: ">=2.12.0 <3.0.0"
dart: ">=2.14.0 <3.0.0"
flutter: ">=1.20.0"

@ -1,6 +1,5 @@
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:dj_printer/dj_printer.dart';
void main() {
const MethodChannel channel = MethodChannel('dj_printer');
@ -17,7 +16,5 @@ void main() {
channel.setMockMethodCallHandler(null);
});
test('getPlatformVersion', () async {
expect(await DjPrinter.platformVersion, '42');
});
test('getPlatformVersion', () async {});
}

Loading…
Cancel
Save