56 |
57 |
58 |
59 |
60 |
61 |
--------------------------------------------------------------------------------
/PrintProject/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/PrintProject/app/src/main/java/printproject/com/printproject/PrintReceipt.java:
--------------------------------------------------------------------------------
1 | package printproject.com.printproject;
2 |
3 | import android.content.Context;
4 | import printproject.com.model.SalesModel;
5 | import printproject.com.utility.Utility;
6 |
7 | /**
8 | * This class is responsible to generate a static sales receipt and to print that receipt
9 | */
10 | public class PrintReceipt {
11 |
12 | public static boolean printBillFromOrder(Context context){
13 | if(BluetoothPrinterActivity.BLUETOOTH_PRINTER.IsNoConnection()){
14 | return false;
15 | }
16 |
17 | double totalBill=0.00, netBill=0.00, totalVat=0.00;
18 |
19 | //LF = Line feed
20 | BluetoothPrinterActivity.BLUETOOTH_PRINTER.Begin();
21 | BluetoothPrinterActivity.BLUETOOTH_PRINTER.LF();
22 | BluetoothPrinterActivity.BLUETOOTH_PRINTER.LF();
23 | BluetoothPrinterActivity.BLUETOOTH_PRINTER.SetAlignMode((byte) 1);//CENTER
24 | BluetoothPrinterActivity.BLUETOOTH_PRINTER.SetLineSpacing((byte) 30); //30 * 0.125mm
25 | BluetoothPrinterActivity.BLUETOOTH_PRINTER.SetFontEnlarge((byte) 0x00);//normal
26 | BluetoothPrinterActivity.BLUETOOTH_PRINTER.BT_Write("Company Name");
27 |
28 | BluetoothPrinterActivity.BLUETOOTH_PRINTER.LF();
29 | BluetoothPrinterActivity.BLUETOOTH_PRINTER.SetAlignMode((byte) 1);
30 | BluetoothPrinterActivity.BLUETOOTH_PRINTER.SetLineSpacing((byte) 30);
31 | BluetoothPrinterActivity.BLUETOOTH_PRINTER.SetFontEnlarge((byte) 0x00);
32 |
33 | //BT_Write() method will initiate the printer to start printing.
34 | BluetoothPrinterActivity.BLUETOOTH_PRINTER.BT_Write("Branch Name: " + "Stuttgart Branch" +
35 | "\nOrder No: " + "1245784256454" +
36 | "\nBill No: " + "554741254854" +
37 | "\nTrn. Date:" + "29/12/2015" +
38 | "\nSalesman:" + "Mr. Salesman");
39 |
40 | BluetoothPrinterActivity.BLUETOOTH_PRINTER.LF();
41 | BluetoothPrinterActivity.BLUETOOTH_PRINTER.BT_Write(context.getResources().getString(R.string.print_line));
42 | BluetoothPrinterActivity.BLUETOOTH_PRINTER.LF();
43 |
44 | BluetoothPrinterActivity.BLUETOOTH_PRINTER.SetAlignMode((byte) 0);//LEFT
45 | BluetoothPrinterActivity.BLUETOOTH_PRINTER.SetLineSpacing((byte) 30); //50 * 0.125mm
46 | BluetoothPrinterActivity.BLUETOOTH_PRINTER.SetFontEnlarge((byte) 0x00);//normal font
47 |
48 | //static sales record are generated
49 | SalesModel.generatedMoneyReceipt();
50 |
51 | for(int i=0;i
2 | PrintProject
3 | Searching...
4 | Select a device to connect
5 | No devices have been paired
6 | No devices found
7 | No printer is connected
8 | Paired Devices
9 | Other Available Devices
10 | Search for devices
11 | Connect a Bluetooth Printer
12 | Print Receipt
13 | Print Option
14 | Inquiry Status
15 | Quit
16 | Connecting...
17 | connected:
18 | Bluetooth is not enabled
19 | "--------------------------------"
20 | Re-connect
21 | Would you like to re-connect with a bluetooth printer?
22 | Yes
23 | No
24 | content description
25 | ScrollingActivity
26 |
27 | "Material is the metaphor.\n\n"
28 |
29 | "A material metaphor is the unifying theory of a rationalized space and a system of motion."
30 | "The material is grounded in tactile reality, inspired by the study of paper and ink, yet "
31 | "technologically advanced and open to imagination and magic.\n"
32 | "Surfaces and edges of the material provide visual cues that are grounded in reality. The "
33 | "use of familiar tactile attributes helps users quickly understand affordances. Yet the "
34 | "flexibility of the material creates new affordances that supercede those in the physical "
35 | "world, without breaking the rules of physics.\n"
36 | "The fundamentals of light, surface, and movement are key to conveying how objects move, "
37 | "interact, and exist in space and in relation to each other. Realistic lighting shows "
38 | "seams, divides space, and indicates moving parts.\n\n"
39 |
40 | "Bold, graphic, intentional.\n\n"
41 |
42 | "The foundational elements of print based design typography, grids, space, scale, color, "
43 | "and use of imagery guide visual treatments. These elements do far more than please the "
44 | "eye. They create hierarchy, meaning, and focus. Deliberate color choices, edge to edge "
45 | "imagery, large scale typography, and intentional white space create a bold and graphic "
46 | "interface that immerse the user in the experience.\n"
47 | "An emphasis on user actions makes core functionality immediately apparent and provides "
48 | "waypoints for the user.\n\n"
49 |
50 | "Motion provides meaning.\n\n"
51 |
52 | "Motion respects and reinforces the user as the prime mover. Primary user actions are "
53 | "inflection points that initiate motion, transforming the whole design.\n"
54 | "All action takes place in a single environment. Objects are presented to the user without "
55 | "breaking the continuity of experience even as they transform and reorganize.\n"
56 | "Motion is meaningful and appropriate, serving to focus attention and maintain continuity. "
57 | "Feedback is subtle yet clear. Transitions are efficient yet coherent.\n\n"
58 |
59 | "3D world.\n\n"
60 |
61 | "The material environment is a 3D space, which means all objects have x, y, and z "
62 | "dimensions. The z-axis is perpendicularly aligned to the plane of the display, with the "
63 | "positive z-axis extending towards the viewer. Every sheet of material occupies a single "
64 | "position along the z-axis and has a standard 1dp thickness.\n"
65 | "On the web, the z-axis is used for layering and not for perspective. The 3D world is "
66 | "emulated by manipulating the y-axis.\n\n"
67 |
68 | "Light and shadow.\n\n"
69 |
70 | "Within the material environment, virtual lights illuminate the scene. Key lights create "
71 | "directional shadows, while ambient light creates soft shadows from all angles.\n"
72 | "Shadows in the material environment are cast by these two light sources. In Android "
73 | "development, shadows occur when light sources are blocked by sheets of material at "
74 | "various positions along the z-axis. On the web, shadows are depicted by manipulating the "
75 | "y-axis only. The following example shows the card with a height of 6dp.\n\n"
76 |
77 | "Resting elevation.\n\n"
78 |
79 | "All material objects, regardless of size, have a resting elevation, or default elevation "
80 | "that does not change. If an object changes elevation, it should return to its resting "
81 | "elevation as soon as possible.\n\n"
82 |
83 | "Component elevations.\n\n"
84 |
85 | "The resting elevation for a component type is consistent across apps (e.g., FAB elevation "
86 | "does not vary from 6dp in one app to 16dp in another app).\n"
87 | "Components may have different resting elevations across platforms, depending on the depth "
88 | "of the environment (e.g., TV has a greater depth than mobile or desktop).\n\n"
89 |
90 | "Responsive elevation and dynamic elevation offsets.\n\n"
91 |
92 | "Some component types have responsive elevation, meaning they change elevation in response "
93 | "to user input (e.g., normal, focused, and pressed) or system events. These elevation "
94 | "changes are consistently implemented using dynamic elevation offsets.\n"
95 | "Dynamic elevation offsets are the goal elevation that a component moves towards, relative "
96 | "to the component’s resting state. They ensure that elevation changes are consistent "
97 | "across actions and component types. For example, all components that lift on press have "
98 | "the same elevation change relative to their resting elevation.\n"
99 | "Once the input event is completed or cancelled, the component will return to its resting "
100 | "elevation.\n\n"
101 |
102 | "Avoiding elevation interference.\n\n"
103 |
104 | "Components with responsive elevations may encounter other components as they move between "
105 | "their resting elevations and dynamic elevation offsets. Because material cannot pass "
106 | "through other material, components avoid interfering with one another any number of ways, "
107 | "whether on a per component basis or using the entire app layout.\n"
108 | "On a component level, components can move or be removed before they cause interference. "
109 | "For example, a floating action button (FAB) can disappear or move off screen before a "
110 | "user picks up a card, or it can move if a snackbar appears.\n"
111 | "On the layout level, design your app layout to minimize opportunities for interference. "
112 | "For example, position the FAB to one side of stream of a cards so the FAB won’t interfere "
113 | "when a user tries to pick up one of cards.\n\n"
114 |
115 | Settings
116 |
117 |
118 |
--------------------------------------------------------------------------------
/PrintProject/app/src/main/java/printproject/com/printproject/BluetoothPrinterActivity.java:
--------------------------------------------------------------------------------
1 | package printproject.com.printproject;
2 |
3 | import android.app.AlertDialog;
4 | import android.content.DialogInterface;
5 | import android.support.v7.app.AppCompatActivity;
6 | import android.os.Bundle;
7 | import java.lang.ref.WeakReference;
8 | import android.app.Activity;
9 | import android.bluetooth.BluetoothAdapter;
10 | import android.bluetooth.BluetoothDevice;
11 | import android.content.Context;
12 | import android.content.Intent;
13 | import android.os.Handler;
14 | import android.os.Message;
15 | import android.util.Log;
16 | import android.view.View;
17 | import android.view.View.OnClickListener;
18 | import android.widget.Button;
19 | import android.widget.ImageView;
20 | import android.widget.TextView;
21 | import android.widget.Toast;
22 | import com.mocoo.hang.rtprinter.driver.Contants;
23 | import com.mocoo.hang.rtprinter.driver.HsBluetoothPrintDriver;
24 |
25 | /**
26 | * @author shohrab.uddin, RONGTA
27 | * This class is responsible to connect with a bluetooth printer
28 | */
29 | public class BluetoothPrinterActivity extends AppCompatActivity {
30 |
31 | private static final String TAG = "BloothPrinterActivity";
32 | private static BluetoothDevice device;
33 | private static Context CONTEXT;
34 | private AlertDialog.Builder alertDlgBuilder;
35 | private static final int REQUEST_CONNECT_DEVICE = 1;
36 | private static final int REQUEST_ENABLE_BT = 2;
37 | private BluetoothAdapter mBluetoothAdapter = null;
38 | public static HsBluetoothPrintDriver BLUETOOTH_PRINTER = null;
39 |
40 | private static Button mBtnConnetBluetoothDevice = null;
41 | private static Button mBtnPrint = null;
42 | private static TextView txtPrinterStatus = null;
43 | private static ImageView mImgPosPrinter = null;
44 |
45 |
46 |
47 |
48 | @Override
49 | public void onCreate(Bundle savedInstanceState) {
50 | super.onCreate(savedInstanceState);
51 | Log.e(TAG, "+++ ON CREATE +++");
52 |
53 | setContentView(R.layout.bluetooth_printer_activity);
54 |
55 | CONTEXT = getApplicationContext();
56 | alertDlgBuilder = new AlertDialog.Builder(BluetoothPrinterActivity.this);
57 |
58 | // Get device's Bluetooth adapter
59 | mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
60 |
61 | // If the adapter is null, then Bluetooth is not available in your device
62 | if (mBluetoothAdapter == null) {
63 | Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
64 | finish();
65 | return;
66 |
67 | }
68 | //Initialize widgets
69 | InitUIControl();
70 | }
71 |
72 | private void InitUIControl(){
73 | txtPrinterStatus = (TextView) findViewById(R.id.txtPrinerStatus);
74 | mBtnConnetBluetoothDevice = (Button)findViewById(R.id.btn_connect_bluetooth_device);
75 | mBtnConnetBluetoothDevice.setOnClickListener(mBtnConnetBluetoothDeviceOnClickListener);
76 | mBtnPrint = (Button)findViewById(R.id.btn_print);
77 | mBtnPrint.setOnClickListener(mBtnPrintOnClickListener);
78 |
79 | mImgPosPrinter = (ImageView)findViewById(R.id.printer_imgPOSPrinter);
80 | }
81 |
82 | @Override
83 | public void onStart() {
84 | super.onStart();
85 | Log.e(TAG, "++ ON START ++");
86 |
87 | // If BT is not on, request that to be enabled.
88 | // initializeBluetoothDevice() will then be called during onActivityResult
89 | if (!mBluetoothAdapter.isEnabled()) {
90 | Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
91 | startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
92 | // Otherwise, setup the chat session
93 | } else {
94 | if (BLUETOOTH_PRINTER == null){
95 | initializeBluetoothDevice();
96 | }else{
97 | if(BLUETOOTH_PRINTER.IsNoConnection()){
98 | mImgPosPrinter.setImageResource(R.drawable.pos_printer_offliine);
99 | }else{
100 | txtPrinterStatus.setText(R.string.title_connected_to);
101 | txtPrinterStatus.append(device.getName());
102 | mImgPosPrinter.setImageResource(R.drawable.pos_printer);
103 | }
104 | }
105 |
106 | }
107 | }
108 |
109 | private void initializeBluetoothDevice() {
110 | Log.d(TAG, "setupChat()");
111 | // Initialize HsBluetoothPrintDriver class to perform bluetooth connections
112 | BLUETOOTH_PRINTER = HsBluetoothPrintDriver.getInstance();//
113 | BLUETOOTH_PRINTER.setHandler(new BluetoothHandler(BluetoothPrinterActivity.this));
114 | }
115 |
116 | /**
117 | * The Handler that gets information back from Bluetooth Devices
118 | */
119 | static class BluetoothHandler extends Handler {
120 | private final WeakReference myWeakReference;
121 |
122 | //Creating weak reference of BluetoothPrinterActivity class to avoid any leak
123 | BluetoothHandler(BluetoothPrinterActivity weakReference) {
124 | myWeakReference = new WeakReference(weakReference);
125 | }
126 | @Override
127 | public void handleMessage(Message msg)
128 | {
129 | BluetoothPrinterActivity bluetoothPrinterActivity = myWeakReference.get();
130 | if (bluetoothPrinterActivity != null) {
131 | super.handleMessage(msg);
132 | Bundle data = msg.getData();
133 | switch (data.getInt("flag")) {
134 | case Contants.FLAG_STATE_CHANGE:
135 | int state = data.getInt("state");
136 | Log.i(TAG, "MESSAGE_STATE_CHANGE: " + state);
137 | switch (state) {
138 | case HsBluetoothPrintDriver.CONNECTED_BY_BLUETOOTH:
139 | txtPrinterStatus.setText(R.string.title_connected_to);
140 | txtPrinterStatus.append(device.getName());
141 | StaticValue.isPrinterConnected=true;
142 | Toast.makeText(CONTEXT,"Connection successful.", Toast.LENGTH_SHORT).show();
143 | mImgPosPrinter.setImageResource(R.drawable.pos_printer);
144 | break;
145 | case HsBluetoothPrintDriver.FLAG_SUCCESS_CONNECT:
146 | txtPrinterStatus.setText(R.string.title_connecting);
147 | break;
148 |
149 | case HsBluetoothPrintDriver.UNCONNECTED:
150 | txtPrinterStatus.setText(R.string.no_printer_connected);
151 | break;
152 | }
153 | break;
154 | case Contants.FLAG_SUCCESS_CONNECT:
155 | txtPrinterStatus.setText(R.string.title_connecting);
156 | break;
157 | case Contants.FLAG_FAIL_CONNECT:
158 | Toast.makeText(CONTEXT,"Connection failed.",Toast.LENGTH_SHORT).show();
159 | mImgPosPrinter.setImageResource(R.drawable.pos_printer_offliine);
160 | break;
161 | default:
162 | break;
163 |
164 | }
165 | }
166 | };
167 | }
168 |
169 | @Override
170 | protected void onActivityResult(int requestCode, int resultCode, Intent data) {
171 | Log.d(TAG, "onActivityResult " + resultCode);
172 | switch (requestCode) {
173 | case REQUEST_CONNECT_DEVICE:
174 | // When DeviceListActivity returns with a device to connect
175 | if (resultCode == Activity.RESULT_OK) {
176 | // Get the device MAC address
177 | String address = data.getExtras()
178 | .getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
179 | // Get the BLuetoothDevice object
180 | device = mBluetoothAdapter.getRemoteDevice(address);
181 | // Attempt to connect to the device
182 | BLUETOOTH_PRINTER.start();
183 | BLUETOOTH_PRINTER.connect(device);
184 | }
185 | break;
186 | case REQUEST_ENABLE_BT:
187 | // When the request to enable Bluetooth returns
188 | if (resultCode == Activity.RESULT_OK) {
189 | // Bluetooth is now enabled, so set up a chat session
190 | initializeBluetoothDevice();
191 | } else {
192 | // User did not enable Bluetooth or an error occured
193 | Log.d(TAG, "BT not enabled");
194 | Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
195 | finish();
196 | }
197 | }
198 | }
199 |
200 |
201 | OnClickListener mBtnQuitOnClickListener = new OnClickListener() {
202 | @Override
203 | public void onClick(View v) {
204 | // Stop the Bluetooth chat services
205 | if (!PrintReceipt.printBillFromOrder(getApplicationContext())){
206 | Toast.makeText(BluetoothPrinterActivity.this,"No printer is connected!!",Toast.LENGTH_LONG).show();
207 | }
208 |
209 | };
210 | };
211 |
212 | OnClickListener mBtnPrintOnClickListener = new OnClickListener() {
213 | public void onClick(View arg0){
214 | PrintReceipt.printBillFromOrder(BluetoothPrinterActivity.this);
215 | }
216 | };
217 |
218 | OnClickListener mBtnConnetBluetoothDeviceOnClickListener = new OnClickListener() {
219 | Intent serverIntent = null;
220 | public void onClick(View arg0){
221 |
222 | //If bluetooth is disabled then ask user to enable it again
223 | if (!mBluetoothAdapter.isEnabled()) {
224 | Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
225 | startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
226 | }else{//If the connection is lost with last connected bluetooth printer
227 | if(BLUETOOTH_PRINTER.IsNoConnection()){
228 | serverIntent = new Intent(BluetoothPrinterActivity.this, DeviceListActivity.class);
229 | startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
230 | }else{ //If an existing connection is still alive then ask user to kill it and re-connect again
231 | alertDlgBuilder.setTitle(getResources().getString(R.string.alert_title));
232 | alertDlgBuilder.setMessage(getResources().getString(R.string.alert_message));
233 | alertDlgBuilder.setNegativeButton(getResources().getString(R.string.alert_btn_negative), new DialogInterface.OnClickListener() {
234 | @Override
235 | public void onClick(DialogInterface dialog, int which) {
236 |
237 | }
238 | }
239 | );
240 | alertDlgBuilder.setPositiveButton(getResources().getString(R.string.alert_btn_positive), new DialogInterface.OnClickListener() {
241 | @Override
242 | public void onClick(DialogInterface dialog, int which) {
243 | BLUETOOTH_PRINTER.stop();
244 | serverIntent = new Intent(BluetoothPrinterActivity.this, DeviceListActivity.class);
245 | startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
246 | }
247 | }
248 | );
249 | alertDlgBuilder.show();
250 |
251 | }
252 | }
253 |
254 | };
255 |
256 | };
257 |
258 | @Override
259 | protected void onDestroy() {
260 | super.onDestroy();
261 | if(BLUETOOTH_PRINTER.IsNoConnection())
262 | BLUETOOTH_PRINTER.stop();
263 | }
264 | }
265 |
--------------------------------------------------------------------------------
/PrintProject/app/src/main/java/printproject/com/printproject/DeviceListActivity.java:
--------------------------------------------------------------------------------
1 |
2 | package printproject.com.printproject;
3 |
4 | import java.util.Set;
5 | import android.app.Activity;
6 | import android.bluetooth.BluetoothAdapter;
7 | import android.bluetooth.BluetoothDevice;
8 | import android.content.BroadcastReceiver;
9 | import android.content.Context;
10 | import android.content.Intent;
11 | import android.content.IntentFilter;
12 | import android.os.Bundle;
13 | import android.util.Log;
14 | import android.view.View;
15 | import android.view.View.OnClickListener;
16 | import android.view.Window;
17 | import android.widget.AdapterView;
18 | import android.widget.AdapterView.OnItemClickListener;
19 | import android.widget.ArrayAdapter;
20 | import android.widget.Button;
21 | import android.widget.ListView;
22 | import android.widget.TextView;
23 |
24 | /**
25 | /**
26 | * @author shohrab.uddin, RONGTA
27 | * This Activity appears when user wants to connect with a printer. It lists any paired devices and
28 | * devices detected in the area after discovery. When a device is chosen
29 | * by the user, the MAC address of the device is sent back to the parent
30 | * Activity in the result Intent.
31 | */
32 | public class DeviceListActivity extends Activity {
33 | // Debugging
34 | private static final String TAG = "DeviceListActivity";
35 | private static final boolean D = true;
36 | public static final String PERMISSIONS_REQUEST_LOCATION=100;
37 | public static final int CURRENT_ANDROID_VERSION = android.os.Build.VERSION.SDK_INT;
38 |
39 |
40 | // Return Intent extra
41 | public static String EXTRA_DEVICE_ADDRESS = "device_address";
42 |
43 | // Member fields
44 | private BluetoothAdapter mBtAdapter;
45 | private ArrayAdapter mPairedDevicesArrayAdapter;
46 | private ArrayAdapter mNewDevicesArrayAdapter;
47 | private AlertDialog.Builder alertDialogBuilder;
48 |
49 | @Override
50 | protected void onCreate(Bundle savedInstanceState) {
51 | super.onCreate(savedInstanceState);
52 | // Setup the window
53 | requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
54 | setContentView(R.layout.bluetooth_device_list);
55 |
56 | // Set result CANCELED incase the user backs out
57 | setResult(Activity.RESULT_CANCELED);
58 |
59 | alertDialogBuilder = new AlertDialog.Builder(
60 | getApplicationContext());
61 |
62 | // Initialize the button to perform device discovery
63 | Button scanButton = (Button) findViewById(R.id.button_scan);
64 | scanButton.setOnClickListener(new OnClickListener() {
65 | public void onClick(View v) {
66 | permissionChecking();
67 | }
68 | });
69 |
70 | // Initialize array adapters. One for already paired devices and
71 | // one for newly discovered devices
72 | mPairedDevicesArrayAdapter = new ArrayAdapter(this, R.layout.list_layout_bluetooth_device);
73 | mNewDevicesArrayAdapter = new ArrayAdapter(this, R.layout.list_layout_bluetooth_device);
74 |
75 | // Find and set up the ListView for paired devices
76 | ListView pairedListView = (ListView) findViewById(R.id.paired_devices);
77 | pairedListView.setAdapter(mPairedDevicesArrayAdapter);
78 | pairedListView.setOnItemClickListener(mDeviceClickListener);
79 |
80 | // Find and set up the ListView for newly discovered devices
81 | ListView newDevicesListView = (ListView) findViewById(R.id.new_devices);
82 | newDevicesListView.setAdapter(mNewDevicesArrayAdapter);
83 | newDevicesListView.setOnItemClickListener(mDeviceClickListener);
84 |
85 | // Register for broadcasts when a device is discovered
86 | IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
87 | this.registerReceiver(mReceiver, filter);
88 |
89 | // Register for broadcasts when discovery has finished
90 | filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
91 | this.registerReceiver(mReceiver, filter);
92 |
93 | // Get the local Bluetooth adapter
94 | mBtAdapter = BluetoothAdapter.getDefaultAdapter();
95 |
96 | // Get a set of currently paired devices
97 | Set pairedDevices = mBtAdapter.getBondedDevices();
98 |
99 | // If there are paired devices, add each one to the ArrayAdapter
100 | if (pairedDevices.size() > 0) {
101 | findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
102 | for (BluetoothDevice device : pairedDevices) {
103 | mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
104 | }
105 | } else {
106 | String noDevices = getResources().getText(R.string.none_paired).toString();
107 | mPairedDevicesArrayAdapter.add(noDevices);
108 | }
109 | }
110 |
111 | private void permissionChecking(){
112 | //--------------------------------------LOCATION Requesting Permission at Run Time--------------------------------------
113 | // Here, thisActivity is the current activity
114 |
115 | if (CURRENT_ANDROID_VERSION >= Build.VERSION_CODES.M) { //Marshmallow
116 |
117 | if (ContextCompat.checkSelfPermission(DeviceListActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION)
118 | != PackageManager.PERMISSION_GRANTED) {
119 |
120 | // Should we show an explanation? This method returns true if the app has requested this
121 | // permission previously and the user denied the request.
122 | if (ActivityCompat.shouldShowRequestPermissionRationale(DeviceListActivity.this,
123 | Manifest.permission.ACCESS_COARSE_LOCATION)) {
124 |
125 | // Show an explanation to the user *asynchronously* -- don't block
126 | // this thread waiting for the user's response! After the user
127 | // sees the explanation, try again to request the permission.
128 |
129 |
130 | alertDialogBuilder.setTitle("Location Service");
131 | alertDialogBuilder
132 | .setMessage("We need to access your device's location service in order to use bluetooth.")
133 | .setCancelable(false)
134 | .setPositiveButton("Allow",new DialogInterface.OnClickListener() {
135 | public void onClick(DialogInterface dialog,int id) {
136 | ActivityCompat.requestPermissions(DeviceListActivity.this,
137 | new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
138 | PERMISSIONS_REQUEST_LOCATION);
139 | dialog.cancel();
140 | }
141 | })
142 | .setNegativeButton("Not allow",new DialogInterface.OnClickListener() {
143 | public void onClick(DialogInterface dialog,int id) {
144 | dialog.cancel();
145 | }
146 | });
147 |
148 | // create alert dialog
149 | AlertDialog alertDialog = alertDialogBuilder.create();
150 | alertDialog.show();
151 | } else {// No explanation needed, we can request the permission.
152 |
153 | ActivityCompat.requestPermissions(DeviceListActivity.this,
154 | new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
155 | PERMISSIONS_REQUEST_LOCATION);
156 |
157 | // MY_PERMISSIONS_REQUEST_EXTERNAL_STORAGE is an
158 | // app-defined int constant. The callback method gets the
159 | // result of the request.
160 | }
161 | }else{ //permission already granted
162 | mNewDevicesArrayAdapter.clear();
163 | doDiscovery();
164 | }
165 | }else{//android version lower than 23
166 | mNewDevicesArrayAdapter.clear();
167 | doDiscovery();
168 | }
169 | }
170 |
171 | //When your app requests permissions, the system presents a dialog box to the user.
172 | //When the user responds, the system invokes your app's onRequestPermissionsResult()
173 | //method, passing it the user response.
174 | @Override
175 | public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
176 |
177 | switch (requestCode) {
178 | case PERMISSIONS_REQUEST_LOCATION: {
179 | // If request is cancelled, the result arrays are empty.
180 | if (grantResults.length > 0
181 | && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
182 | mNewDevicesArrayAdapter.clear();
183 | doDiscovery();
184 |
185 | } else {
186 | Toast.makeText(DeviceListActivity.this,"Permission is Denied!",Toast.LENGTH_LONG).show();
187 | }
188 | return;
189 | }
190 |
191 | // other 'case' lines to check for other
192 | // permissions this app might request
193 | }
194 | }
195 |
196 | @Override
197 | protected void onDestroy() {
198 | super.onDestroy();
199 |
200 | // Make sure we're not doing discovery anymore
201 | if (mBtAdapter != null) {
202 | mBtAdapter.cancelDiscovery();
203 | }
204 |
205 | // Unregister broadcast listeners
206 | this.unregisterReceiver(mReceiver);
207 | }
208 |
209 | /**
210 | * Start device discover with the BluetoothAdapter
211 | */
212 | private void doDiscovery() {
213 | if (D) Log.d(TAG, "doDiscovery()");
214 |
215 | // Indicate scanning in the title
216 | setProgressBarIndeterminateVisibility(true);
217 | setTitle(R.string.scanning);
218 |
219 | // Turn on sub-title for new devices
220 | findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE);
221 |
222 | // If we're already discovering, stop it
223 | if (mBtAdapter.isDiscovering()) {
224 | mBtAdapter.cancelDiscovery();
225 | }
226 |
227 | // Request discover from BluetoothAdapter
228 | mBtAdapter.startDiscovery();
229 | }
230 |
231 |
232 | /**
233 | * The on-click listener for all devices in the ListViews
234 | */
235 | private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
236 | public void onItemClick(AdapterView> av, View v, int arg2, long arg3) {
237 | // Cancel discovery because it's costly and we're about to connect
238 | mBtAdapter.cancelDiscovery();
239 |
240 | // Get the device MAC address, which is the last 17 chars in the View
241 | String info = ((TextView) v).getText().toString();
242 | String address = info.substring(info.length() - 17);
243 |
244 | // Create the result Intent and include the MAC address
245 | Intent intent = new Intent();
246 | intent.putExtra(EXTRA_DEVICE_ADDRESS, address);
247 |
248 | // Set result and finish this Activity
249 | setResult(Activity.RESULT_OK, intent);
250 | finish();
251 | }
252 | };
253 |
254 | /**
255 | * The BroadcastReceiver that listens for discovered devices and
256 | * changes the title when discovery is finished
257 | */
258 | private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
259 | @Override
260 | public void onReceive(Context context, Intent intent) {
261 | String action = intent.getAction();
262 |
263 | // When discovery finds a device
264 | if (BluetoothDevice.ACTION_FOUND.equals(action)) {
265 | // Get the BluetoothDevice object from the Intent
266 | BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
267 | // If it's already paired, skip it, because it's been listed already
268 | if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
269 | mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
270 | }
271 | // When discovery is finished, change the Activity title
272 | } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
273 | setProgressBarIndeterminateVisibility(false);
274 | setTitle(R.string.select_device);
275 | if (mNewDevicesArrayAdapter.getCount() == 0) {
276 | String noDevices = getResources().getText(R.string.none_found).toString();
277 | mNewDevicesArrayAdapter.add(noDevices);
278 | }
279 | }
280 | }
281 | };
282 |
283 |
284 | }
285 |
--------------------------------------------------------------------------------