Last active
February 7, 2023 08:41
-
-
Save mreram/fea12c3cc8208caa951fe17d178565d5 to your computer and use it in GitHub Desktop.
An implementation of an activity for connecting to a Bixolon printer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package ir.eram.printexample; | |
import android.app.ProgressDialog; | |
import android.bluetooth.BluetoothAdapter; | |
import android.bluetooth.BluetoothClass; | |
import android.bluetooth.BluetoothDevice; | |
import android.graphics.Color; | |
import android.graphics.drawable.ColorDrawable; | |
import android.os.AsyncTask; | |
import android.os.Bundle; | |
import android.os.Environment; | |
import android.text.Html; | |
import android.util.Log; | |
import android.view.View; | |
import android.widget.Button; | |
import android.widget.TextView; | |
import android.widget.Toast; | |
import com.actionbarsherlock.app.SherlockActivity; | |
import com.actionbarsherlock.view.MenuItem; | |
import org.apache.http.NameValuePair; | |
import java.io.File; | |
import java.io.FileNotFoundException; | |
import java.io.FileOutputStream; | |
import java.io.IOException; | |
import java.io.InputStream; | |
import java.io.OutputStream; | |
import java.net.HttpURLConnection; | |
import java.net.URL; | |
import java.util.ArrayList; | |
import java.util.List; | |
import java.util.Set; | |
import butterknife.Bind; | |
import butterknife.ButterKnife; | |
import butterknife.OnClick; | |
import ir.eram.printexample.Jason.UserFunctions; | |
import ir.eram.printexample.Session.SessionManager; | |
import ir.eram.printexample.adapter.LoginTBL; | |
import ir.eram.printexample.adapter.PrintTBL; | |
import ir.eram.printexample.database.DatabaseHandler; | |
import jpos.JposException; | |
import jpos.POSPrinter; | |
import jpos.POSPrinterConst; | |
public class PrintActivity extends SherlockActivity { | |
public final int THEME = R.style.Theme_Sherlock_Light; | |
private String ICode; | |
private String username; | |
private String password; | |
private ProgressDialog pd; | |
private static final String CONFIG_FILE_NAME = "jpos.xml"; | |
@Bind(R.id.txtStatus) | |
TextView txtStatus; | |
@Bind(R.id.btnDownload) | |
Button btnDownload; | |
@Bind(R.id.btnPrint) | |
Button btnPrint; | |
String localUrl; | |
private LoginTBL tblL; | |
private DatabaseHandler dbhandler; | |
private SessionManager session; | |
private int userId; | |
private POSPrinter posPrinter; | |
private BluetoothDevice device; | |
private boolean openedPrinter; | |
private int requestId; | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setTheme(THEME); | |
// setTitle(getString(R.string.page_title_coll_detail)); | |
setTitle(Html.fromHtml("<font color='#ffffff'>" | |
+ "چاپ بارنامه" + "</font>")); | |
getSherlock().getActionBar().setIcon(R.drawable.ic_launcher); | |
setContentView(R.layout.activity_print); | |
ButterKnife.bind(this); | |
getSupportActionBar().setDisplayShowTitleEnabled(true); | |
getSupportActionBar().setDisplayUseLogoEnabled(false); | |
getSupportActionBar().setDisplayShowHomeEnabled(true); | |
getSupportActionBar().setDisplayHomeAsUpEnabled(true); | |
getSupportActionBar().setBackgroundDrawable( | |
new ColorDrawable(Color.parseColor("#055bbb"))); | |
findBluetoothDevice(); | |
initUI(); | |
initPrinter(); | |
} | |
private void initPrinter() { | |
if (posPrinter == null) { | |
posPrinter = new POSPrinter(this); | |
try { | |
openFileInput(CONFIG_FILE_NAME); | |
} catch (FileNotFoundException e) { | |
e.printStackTrace(); | |
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show(); | |
createNewConfigFile(); | |
} | |
} | |
} | |
@OnClick(R.id.btnDownload) | |
public void onDownload() { | |
List<NameValuePair> param = new ArrayList<>(); | |
DownloadPDFAsync downloadPDFAsync = new DownloadPDFAsync(); | |
downloadPDFAsync.execute(param); | |
} | |
private void findBluetoothDevice() { | |
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); | |
Set<BluetoothDevice> pairedDevice = bluetoothAdapter.getBondedDevices(); | |
for (BluetoothDevice device : pairedDevice) | |
{ | |
String deviceBTMajorClass = getBTMajorDeviceClass(device.getBluetoothClass().getMajorDeviceClass()); | |
if (deviceBTMajorClass.equals("IMAGING")) { | |
this.device = device; | |
break; | |
} | |
} | |
} | |
@OnClick(R.id.btnPrint) | |
public void doPrint() { | |
try { | |
if (!openedPrinter) { | |
posPrinter.open(device.getName()); | |
posPrinter.claim(0); | |
posPrinter.setDeviceEnabled(true); | |
posPrinter.setAsyncMode(true); | |
openedPrinter = true; | |
} | |
} catch (JposException e) { | |
e.printStackTrace(); | |
try { | |
posPrinter.close(); | |
openedPrinter = false; | |
} catch (JposException e1) { | |
e1.printStackTrace(); | |
} | |
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show(); | |
} | |
printPDF(localUrl); | |
} | |
@OnClick(R.id.btnFindPrinter) | |
public void onSetPrinter() { | |
findBluetoothDevice(); | |
createNewConfigFile(); | |
try { | |
try { | |
posPrinter.close(); | |
} catch (Exception ignored) { | |
} | |
posPrinter.open(device.getName()); | |
posPrinter.claim(0); | |
posPrinter.setDeviceEnabled(true); | |
posPrinter.setAsyncMode(true); | |
openedPrinter = true; | |
Toast.makeText(this, "تنظیم با موفقیت انجام گردید.", Toast.LENGTH_LONG).show(); | |
} catch (JposException e) { | |
e.printStackTrace(); | |
Toast.makeText(this, "تنظیم با مشکلی روبرو گردید لطفا یک بار خارج شوید و دوباره امتحان کنید . ویا دیتا اپلیکیشن را پاک کنید." + e.getMessage(), Toast.LENGTH_LONG).show(); | |
} | |
} | |
private void createNewConfigFile() { | |
try { | |
String content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + | |
"<!DOCTYPE JposEntries PUBLIC \"-//JavaPOS//DTD//EN\"\n" + | |
" \"jpos/res/jcl.dtd\">\n" + | |
"<JposEntries>\n" + | |
" <JposEntry logicalName=\"" + device.getName() + "\" >\n" + | |
" <creation\n" + | |
" factoryClass=\"com.bxl.loader.ServiceInstanceFactory\"\n" + | |
" serviceClass=\"com.bxl.services.posprinter.POSPrinterService\" />\n" + | |
"\n" + | |
" <vendor\n" + | |
" name=\"BIXOLON\"\n" + | |
" url=\"http://www.bixolon.com\" />\n" + | |
"\n" + | |
" <jpos\n" + | |
" category=\"POSPrinter\"\n" + | |
" version=\"1.14\" />\n" + | |
"\n" + | |
" <product\n" + | |
" name=\"" + device.getName() + "\"\n" + | |
" description=\"First Real Waterproof 3 inch Thermal POS Printer\"\n" + | |
" url=\"http://www.bixolon.com\" />\n" + | |
"\n" + | |
" <!-- Other non JavaPOS required property (mostly vendor properties and bus specific properties i.e. RS232 ) -->\n" + | |
" <prop\n" + | |
" name=\"deviceBus\"\n" + | |
" type=\"String\"\n" + | |
" value=\"Bluetooth\" />\n" + | |
" <prop\n" + | |
" name=\"address\"\n" + | |
" type=\"String\"\n" + | |
" value=\"" + device.getAddress() + "\" />\n" + | |
"\n" + | |
" </JposEntry>\n" + | |
"\n" + | |
"</JposEntries>\n"; | |
FileOutputStream fos = null; | |
try { | |
fos = new FileOutputStream(getFilesDir() + "/" + "jpos.xml"); | |
} catch (FileNotFoundException e) { | |
e.printStackTrace(); | |
} | |
try { | |
fos.write(content.getBytes()); | |
openFileInput(CONFIG_FILE_NAME); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show(); | |
} finally { | |
if (fos != null) { | |
try { | |
fos.close(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
}catch (Exception e){ | |
e.printStackTrace(); | |
Toast.makeText(this,e.getMessage(),Toast.LENGTH_LONG).show(); | |
} | |
} | |
private void printPDF(String fileName) { | |
try { | |
int width = 1000; | |
int page = 1; | |
int brightness = 88; | |
int alignment = POSPrinterConst.PTR_PDF_CENTER; | |
posPrinter.printPDF(POSPrinterConst.PTR_S_RECEIPT, fileName, width, | |
alignment, page, brightness); | |
} catch (JposException | NumberFormatException e) { | |
e.printStackTrace(); | |
Toast.makeText(getApplicationContext(), e.getMessage(), | |
Toast.LENGTH_SHORT).show(); | |
} | |
} | |
@Override | |
protected void onDestroy() { | |
super.onDestroy(); | |
try { | |
posPrinter.close(); | |
openedPrinter = true; | |
} catch (JposException e) { | |
e.printStackTrace(); | |
} | |
} | |
private String getBTMajorDeviceClass(int major) { | |
switch (major) { | |
case BluetoothClass.Device.Major.AUDIO_VIDEO: | |
return "AUDIO_VIDEO"; | |
case BluetoothClass.Device.Major.COMPUTER: | |
return "COMPUTER"; | |
case BluetoothClass.Device.Major.HEALTH: | |
return "HEALTH"; | |
case BluetoothClass.Device.Major.IMAGING: | |
return "IMAGING"; | |
case BluetoothClass.Device.Major.MISC: | |
return "MISC"; | |
case BluetoothClass.Device.Major.NETWORKING: | |
return "NETWORKING"; | |
case BluetoothClass.Device.Major.PERIPHERAL: | |
return "PERIPHERAL"; | |
case BluetoothClass.Device.Major.PHONE: | |
return "PHONE"; | |
case BluetoothClass.Device.Major.TOY: | |
return "TOY"; | |
case BluetoothClass.Device.Major.UNCATEGORIZED: | |
return "UNCATEGORIZED"; | |
case BluetoothClass.Device.Major.WEARABLE: | |
return "AUDIO_VIDEO"; | |
default: | |
return "unknown!"; | |
} | |
} | |
private void getUserPass() { | |
tblL = dbhandler.getUserPass(session.getIcode()); | |
} | |
private void initUI() { | |
dbhandler = new DatabaseHandler(this); | |
session = new SessionManager(this); | |
tblL = new LoginTBL(); | |
getUserPass(); | |
userId = tblL.get_id(); | |
Bundle bundle = getIntent().getExtras(); | |
username = bundle.getString("username"); | |
password = bundle.getString("password"); | |
ICode = bundle.getString("icode"); | |
requestId = bundle.getInt("requestId"); | |
List<NameValuePair> param = new ArrayList<>(); | |
DownloadPDFAsync downloadPDFAsync = new DownloadPDFAsync(); | |
downloadPDFAsync.execute(param); | |
} | |
class DownloadPDFAsync extends AsyncTask<List<NameValuePair>, Integer, String> { | |
@Override | |
protected void onPreExecute() { | |
super.onPreExecute(); | |
pd = new ProgressDialog(PrintActivity.this); | |
pd.setMessage(getString(R.string.wait)); | |
pd.setCancelable(false); | |
pd.show(); | |
} | |
@SafeVarargs | |
@Override | |
protected final String doInBackground(List<NameValuePair>... params) { | |
localUrl = Environment.getExternalStorageDirectory().getPath() + "/printexample/" + ICode + "_print.pdf"; | |
if (new File(localUrl).exists()) { | |
return null; | |
} | |
InputStream input = null; | |
OutputStream output = null; | |
HttpURLConnection connection = null; | |
try { | |
URL url = new URL(UserFunctions.PrintURL + "?username=" + username + "&password=" + password + "&Icode=" + ICode); | |
connection = (HttpURLConnection) url.openConnection(); | |
Log.i("urldownload", url.getPath()); | |
connection.connect(); | |
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { | |
return "Server returned HTTP " + connection.getResponseCode() | |
+ " " + connection.getResponseMessage(); | |
} | |
int fileLength = connection.getContentLength(); | |
input = connection.getInputStream(); | |
File directory = new File(Environment.getExternalStorageDirectory().getPath() + "/printexample/"); | |
if (!directory.exists()) | |
directory.mkdirs(); | |
output = new FileOutputStream(localUrl); | |
byte data[] = new byte[4096]; | |
long total = 0; | |
int count; | |
while ((count = input.read(data)) != -1) { | |
if (isCancelled()) { | |
input.close(); | |
return null; | |
} | |
total += count; | |
if (fileLength > 0) // only if total length is known | |
publishProgress((int) (total * 100 / fileLength)); | |
output.write(data, 0, count); | |
} | |
PrintTBL printTBL = new PrintTBL(); | |
printTBL.userId = userId; | |
printTBL.urlLocal = localUrl; | |
printTBL.url = url.getPath(); | |
printTBL.barnameNumber = Integer.parseInt(ICode); | |
printTBL.requestId = requestId; | |
printTBL.save(PrintActivity.this); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
return e.toString(); | |
} finally { | |
try { | |
if (output != null) | |
output.close(); | |
if (input != null) | |
input.close(); | |
} catch (IOException ignored) { | |
} | |
if (connection != null) | |
connection.disconnect(); | |
} | |
return null; | |
} | |
@Override | |
protected void onPostExecute(String s) { | |
super.onPostExecute(s); | |
pd.dismiss(); | |
if (new File(localUrl).exists()) { | |
btnDownload.setVisibility(View.GONE); | |
btnPrint.setVisibility(View.VISIBLE); | |
} else { | |
btnDownload.setVisibility(View.VISIBLE); | |
btnPrint.setVisibility(View.GONE); | |
} | |
} | |
} | |
@Override | |
public boolean onOptionsItemSelected(MenuItem item) { | |
switch (item.getItemId()) { | |
case android.R.id.home: | |
onBackPressed(); | |
return true; | |
} | |
return super.onOptionsItemSelected(item); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment