in ndroidMaifest.xml
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
in settings.gradle
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
mavenCentral()
jcenter() // Warning: this repository is going to shut down soon
maven { url 'https://jitpack.io' }
}
}
in build.gradle
implementation 'com.github.DantSu:ESCPOS-ThermalPrinter-Android:3.2.0'
in Java folder > Package folder>
Create a package directory folder "async", in that folder create 3 java classes.
in AsyncBluetoothEscPosPrint.java
public class AsyncBluetoothEscPosPrint extends AsyncEscPosPrint {
public AsyncBluetoothEscPosPrint(Context context) {
super(context);
}
public AsyncBluetoothEscPosPrint(Context context, OnPrintFinished onPrintFinished) {
super(context, onPrintFinished);
}
protected PrinterStatus doInBackground(AsyncEscPosPrinter... printersData) {
if (printersData.length == 0) {
return new PrinterStatus(null, AsyncEscPosPrint.FINISH_NO_PRINTER);
}
AsyncEscPosPrinter printerData = printersData[0];
DeviceConnection deviceConnection = printerData.getPrinterConnection();
this.publishProgress(AsyncEscPosPrint.PROGRESS_CONNECTING);
if (deviceConnection == null) {
printersData[0] = new AsyncEscPosPrinter(
BluetoothPrintersConnections.selectFirstPaired(),
printerData.getPrinterDpi(),
printerData.getPrinterWidthMM(),
printerData.getPrinterNbrCharactersPerLine()
);
printersData[0].setTextsToPrint(printerData.getTextsToPrint());
} else {
try {
deviceConnection.connect();
} catch (EscPosConnectionException e) {
e.printStackTrace();
}
}
return super.doInBackground(printersData);
}
}
in AsyncEscPosPrint.java
public abstract class AsyncEscPosPrint extends AsyncTask<AsyncEscPosPrinter, Integer, AsyncEscPosPrint.PrinterStatus> {
public final static int FINISH_SUCCESS = 1;
public final static int FINISH_NO_PRINTER = 2;
public final static int FINISH_PRINTER_DISCONNECTED = 3;
public final static int FINISH_PARSER_ERROR = 4;
public final static int FINISH_ENCODING_ERROR = 5;
public final static int FINISH_BARCODE_ERROR = 6;
protected final static int PROGRESS_CONNECTING = 1;
protected final static int PROGRESS_CONNECTED = 2;
protected final static int PROGRESS_PRINTING = 3;
protected final static int PROGRESS_PRINTED = 4;
protected ProgressDialog dialog;
protected WeakReference<Context> weakContext;
protected OnPrintFinished onPrintFinished;
public AsyncEscPosPrint(Context context) {
this(context, null);
}
public AsyncEscPosPrint(Context context, OnPrintFinished onPrintFinished) {
this.weakContext = new WeakReference<>(context);
this.onPrintFinished = onPrintFinished;
}
protected PrinterStatus doInBackground(AsyncEscPosPrinter... printersData) {
if (printersData.length == 0) {
return new PrinterStatus(null, AsyncEscPosPrint.FINISH_NO_PRINTER);
}
this.publishProgress(AsyncEscPosPrint.PROGRESS_CONNECTING);
AsyncEscPosPrinter printerData = printersData[0];
try {
DeviceConnection deviceConnection = printerData.getPrinterConnection();
if(deviceConnection == null) {
return new PrinterStatus(null, AsyncEscPosPrint.FINISH_NO_PRINTER);
}
EscPosPrinter printer = new EscPosPrinter(
deviceConnection,
printerData.getPrinterDpi(),
printerData.getPrinterWidthMM(),
printerData.getPrinterNbrCharactersPerLine(),
new EscPosCharsetEncoding("windows-1252", 16)
);
// printer.useEscAsteriskCommand(true);
this.publishProgress(AsyncEscPosPrint.PROGRESS_PRINTING);
String[] textsToPrint = printerData.getTextsToPrint();
for(String textToPrint : textsToPrint) {
printer.printFormattedTextAndCut(textToPrint);
Thread.sleep(500);
}
this.publishProgress(AsyncEscPosPrint.PROGRESS_PRINTED);
} catch (EscPosConnectionException e) {
e.printStackTrace();
return new PrinterStatus(printerData, AsyncEscPosPrint.FINISH_PRINTER_DISCONNECTED);
} catch (EscPosParserException e) {
e.printStackTrace();
return new PrinterStatus(printerData, AsyncEscPosPrint.FINISH_PARSER_ERROR);
} catch (EscPosEncodingException e) {
e.printStackTrace();
return new PrinterStatus(printerData, AsyncEscPosPrint.FINISH_ENCODING_ERROR);
} catch (EscPosBarcodeException e) {
e.printStackTrace();
return new PrinterStatus(printerData, AsyncEscPosPrint.FINISH_BARCODE_ERROR);
} catch (InterruptedException e) {
e.printStackTrace();
}
return new PrinterStatus(printerData, AsyncEscPosPrint.FINISH_SUCCESS);
}
protected void onPreExecute() {
if (this.dialog == null) {
Context context = weakContext.get();
if (context == null) {
return;
}
this.dialog = new ProgressDialog(context);
this.dialog.setTitle("Printing in progress...");
this.dialog.setMessage("...");
this.dialog.setProgressNumberFormat("%1d / %2d");
this.dialog.setCancelable(false);
this.dialog.setIndeterminate(false);
this.dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
this.dialog.show();
}
}
protected void onProgressUpdate(Integer... progress) {
switch (progress[0]) {
case AsyncEscPosPrint.PROGRESS_CONNECTING:
this.dialog.setMessage("Connecting printer...");
break;
case AsyncEscPosPrint.PROGRESS_CONNECTED:
this.dialog.setMessage("Printer is connected...");
break;
case AsyncEscPosPrint.PROGRESS_PRINTING:
this.dialog.setMessage("Printer is printing...");
break;
case AsyncEscPosPrint.PROGRESS_PRINTED:
this.dialog.setMessage("Printer has finished...");
break;
}
this.dialog.setProgress(progress[0]);
this.dialog.setMax(4);
}
protected void onPostExecute(PrinterStatus result) {
this.dialog.dismiss();
this.dialog = null;
Context context = weakContext.get();
if (context == null) {
return;
}
switch (result.getPrinterStatus()) {
case AsyncEscPosPrint.FINISH_SUCCESS:
new AlertDialog.Builder(context)
.setTitle("Success")
.setMessage("Congratulation ! The texts are printed !")
.show();
break;
case AsyncEscPosPrint.FINISH_NO_PRINTER:
new AlertDialog.Builder(context)
.setTitle("No printer")
.setMessage("The application can't find any printer connected.")
.show();
break;
case AsyncEscPosPrint.FINISH_PRINTER_DISCONNECTED:
new AlertDialog.Builder(context)
.setTitle("Broken connection")
.setMessage("Unable to connect the printer.")
.show();
break;
case AsyncEscPosPrint.FINISH_PARSER_ERROR:
new AlertDialog.Builder(context)
.setTitle("Invalid formatted text")
.setMessage("It seems to be an invalid syntax problem.")
.show();
break;
case AsyncEscPosPrint.FINISH_ENCODING_ERROR:
new AlertDialog.Builder(context)
.setTitle("Bad selected encoding")
.setMessage("The selected encoding character returning an error.")
.show();
break;
case AsyncEscPosPrint.FINISH_BARCODE_ERROR:
new AlertDialog.Builder(context)
.setTitle("Invalid barcode")
.setMessage("Data send to be converted to barcode or QR code seems to be invalid.")
.show();
break;
}
if(this.onPrintFinished != null) {
if (result.getPrinterStatus() == AsyncEscPosPrint.FINISH_SUCCESS) {
this.onPrintFinished.onSuccess(result.getAsyncEscPosPrinter());
} else {
this.onPrintFinished.onError(result.getAsyncEscPosPrinter(), result.getPrinterStatus());
}
}
}
public static class PrinterStatus {
private AsyncEscPosPrinter asyncEscPosPrinter;
private int printerStatus;
public PrinterStatus (AsyncEscPosPrinter asyncEscPosPrinter, int printerStatus) {
this.asyncEscPosPrinter = asyncEscPosPrinter;
this.printerStatus = printerStatus;
}
public AsyncEscPosPrinter getAsyncEscPosPrinter() {
return asyncEscPosPrinter;
}
public int getPrinterStatus() {
return printerStatus;
}
}
public static abstract class OnPrintFinished {
public abstract void onError(AsyncEscPosPrinter asyncEscPosPrinter, int codeException);
public abstract void onSuccess(AsyncEscPosPrinter asyncEscPosPrinter);
}
}
in AsyncEscPosPrinter.java
public class AsyncEscPosPrinter extends EscPosPrinterSize {
private DeviceConnection printerConnection;
private String[] textsToPrint = new String[0];
public AsyncEscPosPrinter(DeviceConnection printerConnection, int printerDpi, float printerWidthMM, int printerNbrCharactersPerLine) {
super(printerDpi, printerWidthMM, printerNbrCharactersPerLine);
this.printerConnection = printerConnection;
}
public DeviceConnection getPrinterConnection() {
return this.printerConnection;
}
public AsyncEscPosPrinter setTextsToPrint(String[] textsToPrint) {
this.textsToPrint = textsToPrint;
return this;
}
public AsyncEscPosPrinter addTextToPrint(String textToPrint) {
String[] tmp = new String[this.textsToPrint.length + 1];
System.arraycopy(this.textsToPrint, 0, tmp, 0, this.textsToPrint.length);
tmp[this.textsToPrint.length] = textToPrint;
this.textsToPrint = tmp;
return this;
}
public String[] getTextsToPrint() {
return this.textsToPrint;
}
}
in MainActivity.java
Button button = (Button) this.findViewById(R.id.button_bluetooth_browse);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
browseBluetoothDevice();
}
});
button = (Button) findViewById(R.id.button_bluetooth);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
printBluetooth();
}
});
/*==============================================================================================
======================================BLUETOOTH PART============================================
==============================================================================================*/
public static final int PERMISSION_BLUETOOTH = 1;
public static final int PERMISSION_BLUETOOTH_ADMIN = 2;
public static final int PERMISSION_BLUETOOTH_CONNECT = 3;
public static final int PERMISSION_BLUETOOTH_SCAN = 4;
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
switch (requestCode) {
case MainActivity.PERMISSION_BLUETOOTH:
case MainActivity.PERMISSION_BLUETOOTH_ADMIN:
case MainActivity.PERMISSION_BLUETOOTH_CONNECT:
case MainActivity.PERMISSION_BLUETOOTH_SCAN:
this.printBluetooth();
break;
}
}
}
private BluetoothConnection selectedDevice;
public void browseBluetoothDevice() {
final BluetoothConnection[] bluetoothDevicesList = (new BluetoothPrintersConnections()).getList();
if (bluetoothDevicesList != null) {
final String[] items = new String[bluetoothDevicesList.length + 1];
items[0] = "Default printer";
int i = 0;
for (BluetoothConnection device : bluetoothDevicesList) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
items[++i] = device.getDevice().getName();
}
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
alertDialog.setTitle("Bluetooth printer selection");
alertDialog.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
int index = i - 1;
if (index == -1) {
selectedDevice = null;
} else {
selectedDevice = bluetoothDevicesList[index];
}
Button button = (Button) findViewById(R.id.button_bluetooth_browse);
button.setText(items[i]);
}
});
AlertDialog alert = alertDialog.create();
alert.setCanceledOnTouchOutside(false);
alert.show();
}
}
public void printBluetooth() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.BLUETOOTH}, MainActivity.PERMISSION_BLUETOOTH);
} else if (ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_ADMIN) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.BLUETOOTH_ADMIN}, MainActivity.PERMISSION_BLUETOOTH_ADMIN);
} else if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S && ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.BLUETOOTH_CONNECT}, MainActivity.PERMISSION_BLUETOOTH_CONNECT);
} else if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S && ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.BLUETOOTH_SCAN}, MainActivity.PERMISSION_BLUETOOTH_SCAN);
} else {
new AsyncBluetoothEscPosPrint(
this,
new AsyncEscPosPrint.OnPrintFinished() {
@Override
public void onError(AsyncEscPosPrinter asyncEscPosPrinter, int codeException) {
Log.e("Async.OnPrintFinished", "AsyncEscPosPrint.OnPrintFinished : An error occurred !");
}
@Override
public void onSuccess(AsyncEscPosPrinter asyncEscPosPrinter) {
Log.i("Async.OnPrintFinished", "AsyncEscPosPrint.OnPrintFinished : Print is finished !");
}
}
)
.execute(this.getAsyncEscPosPrinter(selectedDevice));
}
}
/**
* Asynchronous printing
*/
@SuppressLint("SimpleDateFormat")
public AsyncEscPosPrinter getAsyncEscPosPrinter(DeviceConnection printerConnection) {
SimpleDateFormat format = new SimpleDateFormat("'on' yyyy-MM-dd 'at' HH:mm:ss");
AsyncEscPosPrinter printer = new AsyncEscPosPrinter(printerConnection, 203, 55f, 10);
return printer.addTextToPrint(
"[L]\n" +
"[L]<b>TO:-\n" +
"[L] T.Thinesh.\n" +
"[L] No.03, Thalaimannar Road,\n" +
"[L] Thoddaveli,\n" +
"[L] Mannar.\n" +
"[L] TP: 077 218 7857\n" +
"[L]\n"
);
}
in activity_main.xml
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginEnd="28dp"
android:orientation="horizontal"
android:textAlignment="center"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent">
<Button
android:id="@+id/button_bluetooth_browse"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:text="Default printer" />
<Button
android:id="@+id/button_bluetooth"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Print by bluetooth !" />
</LinearLayout>
Android Studio Tutorials |
0 Comments