Android bluetooth example

complete example to use bluetooth printer. and how to connect to bluetooth device.


public class MainActivity extends AppCompatActivity {

Activity activity;
Context context;

private static final int REQUEST_CODE_PERMISSION = 2;

String[] mPermission = {android.Manifest.permission.READ_PHONE_STATE,
android.Manifest.permission.INTERNET,
android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION,
android.Manifest.permission.ACCESS_NETWORK_STATE,
android.Manifest.permission.BLUETOOTH, Manifest.permission.BLUETOOTH_ADMIN};
private String transType = "SALE";

private ProgressDialog pDialog;

BluetoothAdapter mBluetoothAdapter;
volatile boolean stopWorker;

List bDeviceNames = new ArrayList();

BluetoothSocket mmSocket;
BluetoothDevice mmDevice;

OutputStream mmOutputStream;
InputStream mmInputStream;
Thread workerThread;

byte[] readBuffer;
int readBufferPosition;

private FrameLayout container;

void showProgress() {

pDialog = new ProgressDialog(activity);

pDialog.setMessage("Searching for Device");

pDialog.setCancelable(false);

pDialog.show();
}

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_receipt_payment);

activity = this;
context = getApplicationContext();
app_settings = new AppSettings();

handler = new Handler();

try {
if (Build.VERSION.SDK_INT >= 23) {
if (ActivityCompat.checkSelfPermission(this, mPermission[0])
!= MockPackageManager.PERMISSION_GRANTED ||
ActivityCompat.checkSelfPermission(this, mPermission[1])
!= MockPackageManager.PERMISSION_GRANTED ||
ActivityCompat.checkSelfPermission(this, mPermission[2])
!= MockPackageManager.PERMISSION_GRANTED ||
ActivityCompat.checkSelfPermission(this, mPermission[3])
!= MockPackageManager.PERMISSION_GRANTED ||
ActivityCompat.checkSelfPermission(this, mPermission[4])
!= MockPackageManager.PERMISSION_GRANTED ||
ActivityCompat.checkSelfPermission(this, mPermission[5])
!= MockPackageManager.PERMISSION_GRANTED ||
ActivityCompat.checkSelfPermission(this, mPermission[6])
!= MockPackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, mPermission, REQUEST_CODE_PERMISSION);
// If any permission aboe not allowed by user, this condition will execute every tim, else your else part will work
}
}
} catch (Exception e) {
e.printStackTrace();
}

openBlueTooth();

}

void openBlueTooth() {

//BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);

mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

if(mBluetoothAdapter == null) {
Log.v(("Error","No bluetooth adapter available");
}

if(!mBluetoothAdapter.isEnabled()) {
IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mReceiver, filter);
Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetooth, 0);
}else {

//payment_options();
//findbt will first try to conenct paired deviced if not then it will scan for new devices
//first we will check if device is paired then we can connect
//if device is not paired then we need to scan
findBT();

}
}

void scanForBlutooth() {
IntentFilter filter2 = new IntentFilter();
filter2.addAction(BluetoothDevice.ACTION_FOUND);
filter2.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter2.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mReceiver2, filter2);
mBluetoothAdapter.startDiscovery();
}

void showDeviceChooser() {
Set pairedDevices = mBluetoothAdapter.getBondedDevices();
if(pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {

bDeviceNames.add(device);
}
}
String[] your_array_list = new String[bDeviceNames.size()];

for(int i = 0; i < bDeviceNames.size(); ++i) { your_array_list[i] = bDeviceNames.get(i).getName(); } if(bDeviceNames.size() > 0) {
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle("Choose Bluetooth device")
.setCancelable(false)
.setItems(your_array_list, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// The 'which' argument contains the index position
// of the selected item
app_settings.saveAppData("mosambee", bDeviceNames.get(which).getName());
mmDevice = bDeviceNames.get(which);
try {
openBT();
}catch(Exception e){
e.printStackTrace();
Toast.makeText(context, "Bluetooth device is not available Or Switched Off 2", Toast.LENGTH_LONG).show();

}
}
});
builder.create();
builder.show();
}else {
app_settings.showToast("No device available to choose",activity);
}
}

// this will find a bluetooth printer device
boolean findBT() {

pDialog = new ProgressDialog(activity);

pDialog.setMessage("Connecting to paired device, Please wait ...");

pDialog.setCancelable(false);

pDialog.show();
Boolean found = false;
try {

Set pairedDevices = mBluetoothAdapter.getBondedDevices();

if(pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {

String btprinter = app_settings.getAppData("mosambee");
//Log.v("divname",device.getName() + " " + btprinter);
if (device.getName().equals(btprinter)) {
TextView bluetoothname = (TextView) findViewById(R.id.bluetoothname);
mmDevice = device;
bluetoothname.setText(mmDevice.getName().toString());
found = true;
//openBT();
pDialog.cancel();
break;
}
}
}

if(found == false) {
pDialog.cancel();
app_settings.saveAppData("mosambee","");
scanForBlutooth();
return false;
//Toast.makeText(context, "Bluetooth device is not available Or Switched Off 1", Toast.LENGTH_LONG).show();
}else {
return true;
}

}catch(Exception e){
e.printStackTrace();
Toast.makeText(context, "Bluetooth device is not available Or Switched Off 2", Toast.LENGTH_LONG).show();
pDialog.cancel();
e.printStackTrace();
}
return false;
}

//below can be used to print reciept. we can use this code in future

void openBT() throws IOException {
try {

// Standard SerialPortService ID
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
mmSocket.connect();
//mmOutputStream = mmSocket.getOutputStream();
//mmInputStream = mmSocket.getInputStream();

///beginListenForData();

//closeBT();

} catch (Exception e) {

e.printStackTrace();
}
}

// close the connection to bluetooth printer.
void closeBT() throws IOException {
try {
stopWorker = true;
mmOutputStream.close();
mmInputStream.close();
mmSocket.close();
//myLabel.setText("Bluetooth Closed");
} catch (Exception e) {
e.printStackTrace();
}
}

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);

if (mCropImageUri != null && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// required permissions granted, start crop image activity;
startCropImageActivity(mCropImageUri);
} else {
Toast.makeText(context, "Cancelling, required permissions are not granted", Toast.LENGTH_LONG).show();
}

if (requestCode == REQUEST_CODE_PERMISSION) {
if (grantResults.length > 0 &&
grantResults[0] == MockPackageManager.PERMISSION_GRANTED &&
grantResults[1] == MockPackageManager.PERMISSION_GRANTED &&
grantResults[2] == MockPackageManager.PERMISSION_GRANTED &&
grantResults[3] == MockPackageManager.PERMISSION_GRANTED &&
grantResults[4] == MockPackageManager.PERMISSION_GRANTED &&
grantResults[5] == MockPackageManager.PERMISSION_GRANTED &&
grantResults[6] == MockPackageManager.PERMISSION_GRANTED) {
Toast.makeText(activity, "Permissions granted!!!", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(activity, "Permission not granted!!!", Toast.LENGTH_LONG).show();
}
}
}

// this will send text data to be printed by the bluetooth printer
void printData() throws IOException {
try {

/* TextView receipt_company_name = (TextView) findViewById(R.id.receipt_company_name);
TextView receipt_party_code = (TextView) findViewById(R.id.receipt_party_code);
TextView receipt_user_name = (TextView) findViewById(R.id.receipt_user_name);
TextView receipt_emi = (TextView) findViewById(R.id.receipt_emi);
TextView receipt_over_due = (TextView) findViewById(R.id.receipt_over_due);
TextView receipt_incidental = (TextView) findViewById(R.id.receipt_incidental);
TextView receipt_pantly = (TextView) findViewById(R.id.receipt_pantly);
TextView receipt_total = (TextView) findViewById(R.id.receipt_total);

String currentTimeString = new SimpleDateFormat("dd/MM/yyyy").format(new Date());

Date c = Calendar.getInstance().getTime();
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy");
String formattedDate = df.format(c);
//String currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());

String msg = "";
msg += " " + receipt_company_name.getText().toString();

msg += System.getProperty("line.separator")+" ";
msg += "-----------------------------------";
msg += System.getProperty("line.separator");
msg += System.getProperty("line.separator");
msg += System.getProperty("line.separator");

mmOutputStream.write(msg.getBytes());

} catch (Exception e) {
e.printStackTrace();
//Toast.makeText(context, "Bluetooth Print is not available Or Switched Off", Toast.LENGTH_LONG).show();
AskBluToothFindAndOpen();

}
}
/*
* after opening a connection to bluetooth printer device,
* we have to listen and check if a data were sent to be printed.
*/
void beginListenForData() {
try {
final Handler handler = new Handler();

// this is the ASCII code for a newline character
final byte delimiter = 10;

stopWorker = false;
readBufferPosition = 0;
readBuffer = new byte[1024];

workerThread = new Thread(new Runnable() {
public void run() {

while (!Thread.currentThread().isInterrupted() && !stopWorker) {

try {

int bytesAvailable = mmInputStream.available();

if (bytesAvailable > 0) {

byte[] packetBytes = new byte[bytesAvailable];
mmInputStream.read(packetBytes);

for (int i = 0; i < bytesAvailable; i++) { byte b = packetBytes[i]; if (b == delimiter) { byte[] encodedBytes = new byte[readBufferPosition]; System.arraycopy( readBuffer, 0, encodedBytes, 0, encodedBytes.length ); // specify US-ASCII encoding final String data = new String(encodedBytes, "US-ASCII"); readBufferPosition = 0; // tell the user data were sent to bluetooth printer device handler.post(new Runnable() { public void run() { //myLabel.setText(data); } }); } else { readBuffer[readBufferPosition++] = b; } } } } catch (IOException ex) { stopWorker = true; } } } }); workerThread.start(); } catch (Exception e) { e.printStackTrace(); } } void AskBluToothFindAndOpen() { // Add the buttons AlertDialog.Builder builder = new AlertDialog.Builder(activity,R.style.MyDialogTheme); builder.setTitle("Bluetooth"); builder.setMessage("Switch on bluetooth Printer and click on connect") .setPositiveButton(R.string.findopen, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // User clicked OK button findBT(); } }); builder.setNegativeButton(R.string.closeask, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // User cancelled the dialog } }); // Set other dialog properties // Create the AlertDialog builder.create(); builder.show(); } private final BroadcastReceiver mReceiver2 = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) { //discovery starts, we can show progress dialog or perform other tasks showProgress(); } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { pDialog.cancel(); showDeviceChooser(); //discovery finishes, dismis progress dialog } else if (BluetoothDevice.ACTION_FOUND.equals(action)) { //bluetooth device found BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); bDeviceNames.add(device); } } }; private final BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) { final int bluetoothState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR); switch (bluetoothState) { case BluetoothAdapter.STATE_ON: findBT(); /*IntentFilter filter = new IntentFilter(); filter.addAction(BluetoothDevice.ACTION_FOUND); filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED); filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); registerReceiver(mReceiver2, filter); mBluetoothAdapter.startDiscovery(); //Bluethooth is on, now you can performregisterReceiver your tasks //showDeviceChooser(); break;*/ } } } }; }

Leave a Reply

Your email address will not be published. Required fields are marked *

fourteen + 1 =