private final BroadcastReceiver receiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
}
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
try {
if (device.getName() != null) {
if (device.getName().equals("HMSoft")){
Toast.makeText(MainActivity.this, device.getName(), Toast.LENGTH_SHORT).show();
try {
blueSocket = device.createRfcommSocketToServiceRecord(applicationUUID);
Toast.makeText(MainActivity.this, "A", Toast.LENGTH_SHORT).show();
blueAdapter.cancelDiscovery();
Toast.makeText(MainActivity.this, "B", Toast.LENGTH_SHORT).show();
blueSocket.connect();
Toast.makeText(MainActivity.this, "Connected!", Toast.LENGTH_SHORT).show();
} catch (Exception ex){
System.out.println(ex.getMessage());
}
}
}
}catch (Exception ex){
System.out.println(ex.getMessage());
}
bluetoothDevices.add(device);
String deviceName = device.getName();
String deviceHardwareAddress = device.getAddress();
System.out.println(deviceName);
System.out.println(deviceHardwareAddress);
}
}
When you click on the button that activates the execution of this code, the button itself freezes.
Errors:
W/BluetoothAdapter: getBluetoothService() called with no BluetoothManagerCallback
I/System.out: read failed, socket might closed or timeout, read ret: -1
Related
I'm an Android-noob and unfortunately I have to create an application that will send and receive data from a device (ESP32) using Bluetooth Classic HID. I am able to find the device but I can't establish the connection in any way. I've been struggling with this for a few days, maybe someone could point me the way?
Android permissions
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
<uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
MainActivity class
#SuppressLint({"MissingPermission"})
public class MainActivity extends AppCompatActivity {
public static final String TAG = "MainActivity";
public static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
//public static final UUID MY_UUID = UUID.fromString("00001124-0000-1000-8000-00805F9B34FB");
Boolean secured = false;
public BluetoothAdapter mBluetoothAdapter;
public ArrayList<BluetoothDevice> availableDevices = new ArrayList();
public BluetoothDevice connectedDevice;
public String usePin = "";
public static String MY_DEVICE_NAME = "MY_DEVICE";
public static String MY_DEVICE_MAC_ADDRESS = "B4:8A:0A:4E:FF:8E";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
// Device doesn't support Bluetooth
Log.e(TAG, "Device doesn't support Bluetooth");
return;
}
if (!mBluetoothAdapter.isEnabled()) {
// Bluetooth is not enabled, ask the user to enable it
Log.d(TAG, "Bluetooth is not enabled");
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
return;
}
mBluetoothAdapter.enable();
}
IntentFilter filter = new IntentFilter("android.bluetooth.device.action.FOUND");
filter.addAction("android.bluetooth.adapter.action.DISCOVERY_FINISHED");
registerReceiver(discoverFinishHandler, filter);
IntentFilter filter2 = new IntentFilter("android.bluetooth.device.action.PAIRING_REQUEST");
registerReceiver(pairRequestHandler, filter2);
// Buttons
Button btnToggle = findViewById(R.id.btnToggle);
btnToggle.setOnClickListener(v -> {
if(mBluetoothAdapter.isDiscovering())
{
Log.e(TAG, "Stop discovering bt devices");
mBluetoothAdapter.cancelDiscovery();
}
else
{
Log.e(TAG, "Start discovering bt devices");
StartDiscovery();
}
});
Button connectToggle = findViewById(R.id.connectToggle);
connectToggle.setOnClickListener(v -> {
Log.e(TAG, "Connecting...");
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
connectedDevice = mBluetoothAdapter.getRemoteDevice(MY_DEVICE_MAC_ADDRESS);
if(connectedDevice != null && connectedDevice.getName() != null)
{
Log.e(TAG, connectedDevice.getName() + " FOUND!");
BluetoothThread bluetoothThread = new BluetoothThread(connectedDevice, secured);
bluetoothThread.start();
}
else
{
Log.e(TAG, "DEVICE NOT FOUND!");
}
});
Button logdevicesButton = findViewById(R.id.logdevicesButton);
logdevicesButton.setOnClickListener(v -> {
Log.e(TAG, "Avaliable devices:");
for (BluetoothDevice device : availableDevices)
{
Log.e(TAG, device.getName() + " | " + device.getAddress());
}
Set<BluetoothDevice> pairedDevices = BluetoothAdapter.getDefaultAdapter().getBondedDevices();
if (pairedDevices.size() < 1) {
Log.e(TAG, "No bonded devieces.");
}
else
{
Log.e(TAG, "Bonded devices:");
if (pairedDevices.size() > 0) {
for (BluetoothDevice d : pairedDevices) {
Log.e(TAG, d.getName() + " | " + d.getAddress());
}
}
}
if (pairedDevices.size() < 1)
{
Log.e(TAG, "No connected devices.");
}
else
{
LogConnectedDevices(BluetoothProfile.GATT, "GATT");
LogConnectedDevices(BluetoothProfile.GATT_SERVER, "GATT SERVER");
}
});
}
public void StartDiscovery() {
availableDevices.clear();
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (!mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.enable();
}
mBluetoothAdapter.startDiscovery();
Log.e(TAG, "Start Discovery...");
}
public void LogConnectedDevices(Integer profile, String profileName)
{
BluetoothManager bluetoothManager = (BluetoothManager) getApplicationContext().getSystemService(Context.BLUETOOTH_SERVICE);
List<BluetoothDevice> devices = bluetoothManager.getConnectedDevices(profile);
if(devices.size()<1)
{
Log.e(TAG, "No connected devices [" + profileName + "]");
return;
}
Log.e(TAG, "Connected devices [" + profileName + "]:");
for (BluetoothDevice d : devices)
{
Log.e(TAG, d.getName() + " | " + d.getAddress());
}
}
private final BroadcastReceiver discoverFinishHandler = new BroadcastReceiver()
{
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
if ("android.bluetooth.device.action.FOUND".equals(action))
{
BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra("android.bluetooth.device.extra.DEVICE");
if (!availableDevices.contains(device))
{
availableDevices.add(device);
Log.e(TAG, "Discover: " + device.getName() + "(" + device.getAddress() + ")");
}
}
else if ("android.bluetooth.adapter.action.DISCOVERY_FINISHED".equals(action))
{
Log.e(TAG, "Discovery Finished ");
}
}
};
private final BroadcastReceiver pairRequestHandler = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
if (!usePin.equals("")) {
String action = intent.getAction();
if (action.equals("android.bluetooth.device.action.PAIRING_REQUEST")) {
try {
Log.e(TAG, "Start Connecting with PIN....");
this.abortBroadcast();
BluetoothDevice device = (BluetoothDevice)intent.getParcelableExtra("android.bluetooth.device.extra.DEVICE");
byte[] pinBytes = usePin.getBytes(StandardCharsets.UTF_8);
device.setPin(pinBytes);
device.setPairingConfirmation(true);
} catch (Exception var6) {
Log.e(TAG, "Error occurs when trying to auto pair");
var6.printStackTrace();
}
}
}
}
};
}
Bluetooth thread
#SuppressLint({"MissingPermission"})
public class BluetoothThread extends Thread {
private BluetoothSocket mSocket;
private InputStream mInStream;
BluetoothDevice mDevice;
public BluetoothThread(final BluetoothDevice device, final Boolean secured) {
BluetoothSocket tmp = null;
mDevice = device;
try {
if(secured)
tmp = device.createRfcommSocketToServiceRecord(MainActivity.MY_UUID);
else
tmp = device.createInsecureRfcommSocketToServiceRecord(MainActivity.MY_UUID);
} catch (IOException e) {
Log.e(MainActivity.TAG, "Socket create() failed", e);
}
mSocket = tmp;
}
public void run() {
Log.e(MainActivity.TAG, mDevice.getName() + " bluetooth thread started");
try {
mSocket.connect();
mInStream = mSocket.getInputStream();
byte[] buffer = new byte[1024];
int bytes;
while (true) {
Log.e(MainActivity.TAG, "reading data...");
try {
Log.e(MainActivity.TAG, "reading data...");
bytes = mInStream.read(buffer);
// Do something with the received data
Log.e(MainActivity.TAG, "recieved data: " + String.valueOf(bytes));
} catch (IOException e) {
Log.e(MainActivity.TAG, "Error reading from input stream", e);
break;
}
}
} catch (IOException e) {
Log.e(MainActivity.TAG, "Error connecting to device", e);
}
}
public void cancel() {
try {
mSocket.close();
} catch (IOException e) {
Log.e(MainActivity.TAG, "Error closing socket", e);
}
}
}
I already achieved to write NFC tag. The problem was the tag needs to stay on device before you click the "write" button. Heres my code
try {
if(myTag==null){
Toast.makeText(this, "TAP YOUR TAG!", Toast.LENGTH_SHORT ).show();
}else{
write(tagData,myTag);
Toast.makeText(this, "Tag Written!", Toast.LENGTH_SHORT ).show();
}
} catch (IOException e) {
Toast.makeText(this, "Error Writing!", Toast.LENGTH_SHORT ).show();
e.printStackTrace();
} catch (FormatException e) {
Toast.makeText(this, "NFC Format Error!", Toast.LENGTH_SHORT ).show();
e.printStackTrace();
}
}
private void write(String text, Tag tag) throws IOException, FormatException {
NdefRecord[] records = { createRecord(text) };
NdefMessage message = new NdefMessage(records);
Ndef ndef = Ndef.get(tag);
if (ndef != null) {
ndef.connect();
ndef.writeNdefMessage(message);
ndef.close();
} else {
NdefFormatable ndefFormatable = NdefFormatable.get(tag);
if (ndefFormatable != null) {
ndefFormatable.connect();
ndefFormatable.format(message);
ndefFormatable.close();
} else {
Toast.makeText(this, "Tag cannot be written!", Toast.LENGTH_LONG).show();
}
}
}
And the button is this (I used Onclick view)
public void confirmInput (View v){
writeNFC();
}
What I want is the user will fill up the input, click the button (after the button was clicked, show dialog that states "tap your tag") and then input will write the tag (close the dialog)
I think this way it would be more friendly user. Thanks
As you can see I made an app which sends data from an Android device to a Bluetooth module. Everything works perfectly except for one little thing: every time I want to open the app I should've already turned on Bluetooth through my phone settings or the app will crash, and I have to reopen it after turning on Bluetooth so it will run properly.
I've designed a Bluetooth click listener button myself but it still crashes while I enable it via button.
Can you help me find the mistake in my code?
public class MainActivity extends AppCompatActivity {
private static final String TAG = "bluetooth1";
Button btnsend ;
EditText edttext ;
Button btnOnOff;
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
// SPP UUID service
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// MAC-address of Bluetooth module (you must edit this line)
private static String address = "20:16:06:28:17:83";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnsend = (Button) findViewById(R.id.btnsend);
edttext = (EditText) findViewById(R.id.edttxt);
btnOnOff = (Button) findViewById(R.id.btnOnOff);
btAdapter = BluetoothAdapter.getDefaultAdapter();
btnOnOff.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
if (btAdapter.isEnabled()) {
btAdapter.disable();
Toast.makeText(getApplicationContext(), " Disabling Bluetooth", Toast.LENGTH_SHORT).show();
} else {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent,1);
Toast.makeText(getApplicationContext(), " Enabling Bluetooth", Toast.LENGTH_SHORT).show();
}
}
});
edttext.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD);
edttext.setTransformationMethod(new NumericKeyBoardTransformationMethod());
btnsend.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
String dataTransmit = edttext.getText().toString();
if (dataTransmit != null) {
sendData(dataTransmit);
} else {
Toast.makeText(getApplicationContext(), "Please type something first", Toast.LENGTH_SHORT).show();
}
}
});
}
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
if(Build.VERSION.SDK_INT >= 10) {
try {
final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[] { UUID.class });
return (BluetoothSocket) m.invoke(device, MY_UUID);
} catch (Exception e) {
Toast.makeText(getBaseContext(), "Could not Insecure", Toast.LENGTH_SHORT).show();
}
}
return device.createRfcommSocketToServiceRecord(MY_UUID);
}
#Override
public void onResume() {
super.onResume();
// Set up a pointer to the remote node using it's address.
BluetoothDevice device = btAdapter.getRemoteDevice(address);
// Two things are needed to make a connection:
// A MAC address, which we got above.
// A Service ID or UUID. In this case we are using the
// UUID for SPP.
try {
btSocket = createBluetoothSocket(device);
} catch (IOException e1) {
errorExit("Fatal Error", "In onResume() and socket create failed: " + e1.getMessage() + ".");
}
btAdapter.cancelDiscovery();
// Establish the connection. This will block until it connects.
Toast.makeText(getBaseContext(), "Connecting", Toast.LENGTH_SHORT).show();
try {
btSocket.connect();
Toast.makeText(getBaseContext(), "Connecting Ok", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
}
}
// Create a data stream so we can talk to server.
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {
errorExit("Fatal Error", "In onResume() and output stream creation failed:" + e.getMessage() + ".");
}
}
#Override
public void onPause() {
super.onPause();
if (outStream != null) {
try {
outStream.flush();
} catch (IOException e) {
errorExit("Fatal Error", "In onPause() and failed to flush output stream: " + e.getMessage() + ".");
}
}
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
}
}
private void errorExit(String title, String message) {
Toast.makeText(getBaseContext(), title + " - " + message, Toast.LENGTH_LONG).show();
finish();
}
private void sendData(String message) {
byte[] msgBuffer = message.getBytes();
try {
outStream.write(msgBuffer);
} catch (IOException e) {
String msg = "In onResume() and an exception occurred during write: " + e.getMessage();
if (address.equals("20:16:06:28:17:83"))
msg = msg + ".\n\nUpdate your server address from 20:16:06:28:17:83 to the correct address on line 35 in the java code";
msg = msg + ".\n\nCheck that the SPP UUID: " + MY_UUID.toString() + " exists on server.\n\n";
errorExit("Fatal Error", msg);
}
}
}
You have to check if BT is enabled. Try with this:
protected void checkBTState() {
mBtAdapter = BluetoothAdapter.getDefaultAdapter();
if(mBtAdapter == null) {
String message = getResources().getText(R.string.bluetooth_not_supported).toString();
Toast.makeText(getBaseContext(), message, Toast.LENGTH_SHORT).show();
} else {
if (mBtAdapter.isEnabled()) {
Log.d(TAG, "...Bluetooth ON...");
} else {
// Prompt user to turn on Bluetooth //
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
}
Put it in onResume
#Override
public void onResume() {
super.onResume();
checkBTState();
// ...
// some code
// ...
}
Hi i am actually working on app to send command line on the terminal of my Raspberry PI 3.
I wouldlike when i press the button save for example to send the command "ls" to my RPI3.
Acutally, I've got some problem with my object BluetoothconnectionService.
I think I can't send data because my object is not declared on my activity "Accueil" ? `
BluetoothConnectionService.java :
public class BluetoothConnectionService {
private static final String TAG = "BluetoothConnectionServ";
private static final String appName = "MYAPP";
private static final UUID MY_UUID_INSECURE = UUID.fromString("8ce255c0-200a-11e0-ac64-0800200c9a66");
private final BluetoothAdapter mBluetoothAdapter;
private ConnectedThread mConnectedThread;
private AcceptThread mInsecureAcceptThread;
private ConnectThread mConnectThread;
private BluetoothDevice mmDevice;
private UUID deviceUUID;
ProgressDialog mProgressDialog;
Context mContext;
public BluetoothConnectionService(Context context) {
mContext = context;
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
start();
}
private class AcceptThread extends Thread {
// The local server socket
private final BluetoothServerSocket mmServerSocket;
private BluetoothSocket socket = null;
private InputStream mmInStream;
private String device;
public AcceptThread(){
BluetoothServerSocket tmp = null;
// Create a new listening server socket
try{
tmp = mBluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord(appName, MY_UUID_INSECURE);
Log.d(TAG, "AcceptThread: Setting up Server using: " + MY_UUID_INSECURE);
}catch (IOException e){
Log.e(TAG, "AcceptThread: IOException: " + e.getMessage() );
}
mmServerSocket = tmp;
}
public void run(){
Log.d(TAG, "run: AcceptThread Running.");
BluetoothSocket socket = null;
try{
// This is a blocking call and will only return on a
// successful connection or an exception
Log.d(TAG, "run: RFCOM server socket start.....");
socket = mmServerSocket.accept();
Log.d(TAG, "run: RFCOM server socket accepted connection.");
}catch (IOException e){
Log.e(TAG, "AcceptThread: IOException: " + e.getMessage() );
}
//talk about this is in the 3rd
if(socket != null){
connected(socket,mmDevice);
}
Log.i(TAG, "END mAcceptThread ");
}
public void cancel() {
Log.d(TAG, "cancel: Canceling AcceptThread.");
try {
mmServerSocket.close();
} catch (IOException e) {
Log.e(TAG, "cancel: Close of AcceptThread ServerSocket failed. " + e.getMessage() );
}
}
}
private class ConnectThread extends Thread {
private BluetoothSocket mmSocket;
public ConnectThread(BluetoothDevice device, UUID uuid) {
Log.d(TAG, "ConnectThread: started.");
mmDevice = device;
deviceUUID = uuid;
}
public void run(){
BluetoothSocket tmp = null;
Log.i(TAG, "RUN mConnectThread ");
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try {
Log.d(TAG, "ConnectThread: Trying to create InsecureRfcommSocket using UUID: "
+MY_UUID_INSECURE );
tmp = mmDevice.createRfcommSocketToServiceRecord(deviceUUID);
} catch (IOException e) {
Log.e(TAG, "ConnectThread: Could not create InsecureRfcommSocket " + e.getMessage());
}
mmSocket = tmp;
// Always cancel discovery because it will slow down a connection
mBluetoothAdapter.cancelDiscovery();
// Make a connection to the BluetoothSocket
try {
// This is a blocking call and will only return on a
// successful connection or an exception
mmSocket.connect();
Log.d(TAG, "run: ConnectThread connected.");
} catch (IOException e) {
// Close the socket
try {
mmSocket.close();
Log.d(TAG, "run: Closed Socket.");
} catch (IOException e1) {
Log.e(TAG, "mConnectThread: run: Unable to close connection in socket " + e1.getMessage());
}
Log.d(TAG, "run: ConnectThread: Could not connect to UUID: " + MY_UUID_INSECURE );
}
//will talk about this in the 3rd video
connected(mmSocket,mmDevice);
}
public void cancel() {
try {
Log.d(TAG, "cancel: Closing Client Socket.");
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "cancel: close() of mmSocket in Connectthread failed. " + e.getMessage());
}
}
}
public synchronized void start() {
Log.d(TAG, "start");
// Cancel any thread attempting to make a connection
if (mConnectThread != null) {
mConnectThread.cancel();
mConnectThread = null;
}
if (mInsecureAcceptThread == null) {
mInsecureAcceptThread = new AcceptThread();
mInsecureAcceptThread.start();
}
}
public void startClient(BluetoothDevice device,UUID uuid){
Log.d(TAG, "startClient: Started.");
//initprogress dialog
mProgressDialog = ProgressDialog.show(mContext,"Connecting Bluetooth"
,"Please Wait...",true);
mConnectThread = new ConnectThread(device, uuid);
mConnectThread.start();
}
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
Log.d(TAG, "ConnectedThread: Starting.");
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
int error=2;
int i;
//dismiss the progressdialog when connection is established
try{
mProgressDialog.dismiss();
error=1;
}catch (NullPointerException e){
e.printStackTrace();
error=0;
}
try {
tmpIn = mmSocket.getInputStream();
tmpOut = mmSocket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run(){
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
final String strReceived = new String(buffer,0,bytes);
final String strByteCnt = String.valueOf(bytes) + "bytes received. \n";
// Send the obtained bytes to the UI activity
} catch (IOException e) {
Log.e(TAG, "write: Error reading Input Stream. " + e.getMessage() );
break;
}
}
}
//Call this from the main activity to send data to the remote device
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
} catch (IOException e) {
Log.e(TAG, "write: Error writing to output stream. " + e.getMessage() );
}
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
private void connected(BluetoothSocket mmSocket, BluetoothDevice mmDevice) {
Log.d(TAG, "connected: Starting.");
// Start the thread to manage the connection and perform transmissions
mConnectedThread = new ConnectedThread(mmSocket);
mConnectedThread.start();
}
public void write(byte[] out) {
// Create temporary object
ConnectedThread r;
// Synchronize a copy of the ConnectedThread
Log.d(TAG, "write: Write Called.");
//perform the write
mConnectedThread.write(out);
}
}
MainActivity.java :`
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener{
// variables
private static final String TAG = "MainActivity";
private Uri[] mFileUris = new Uri[10];
private static final UUID MY_UUID_INSECURE = UUID.fromString("8ce255c0-200a-11e0-ac64-0800200c9a66");
public ArrayList<BluetoothDevice> mBTDevices = new ArrayList<>();
public DeviceListAdapter mDeviceListAdapter;
// Bluetooth object
BluetoothAdapter mBluetoothAdapter;
BluetoothConnectionService mBluetoothConnection;
BluetoothDevice mBTDevice;
// variables button
Button btnStartConnection;
Button scan;
// Image button
ImageButton btnONOFF;
// Variables affichages
StringBuilder messages;
ListView lvNewDevices;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Constructor
mBTDevices = new ArrayList<>();
messages = new StringBuilder();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
// list findViewbyID
btnONOFF = (ImageButton) findViewById(R.id.bluetooth_on_off);
scan = (Button) findViewById(R.id.scan);
btnStartConnection = (Button) findViewById(R.id.Connect);
lvNewDevices = (ListView) findViewById(R.id.lvNewDevices);
// divers
registerReceiver(mBroadcastReceiver4, filter);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
lvNewDevices.setOnItemClickListener(MainActivity.this);
// ON/OFF BLUETOOTH
btnONOFF.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
enableDisableBT();
}
});
// SCAN
scan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
btnDiscover();
btnEnableDisable_Discoverable();
}
});
// CONNECTION
btnStartConnection.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startConnection();
}
});
}
// 4 BroadcastReceiver
// Create a BroadcastReceiver for ACTION_FOUND
private final BroadcastReceiver mBroadcastReceiver1 = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (action.equals(mBluetoothAdapter.ACTION_STATE_CHANGED)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, mBluetoothAdapter.ERROR);
switch(state){
case BluetoothAdapter.STATE_OFF:
Log.d(TAG, "onReceive: STATE OFF");
break;
case BluetoothAdapter.STATE_TURNING_OFF:
Log.d(TAG, "mBroadcastReceiver1: STATE TURNING OFF");
break;
case BluetoothAdapter.STATE_ON:
Log.d(TAG, "mBroadcastReceiver1: STATE ON");
break;
case BluetoothAdapter.STATE_TURNING_ON:
Log.d(TAG, "mBroadcastReceiver1: STATE TURNING ON");
break;
}
}
}
};
private final BroadcastReceiver mBroadcastReceiver2 = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED)) {
int mode = intent.getIntExtra(BluetoothAdapter.EXTRA_SCAN_MODE, BluetoothAdapter.ERROR);
switch (mode) {
//Device is in Discoverable Mode
case BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE:
Log.d(TAG, "mBroadcastReceiver2: Discoverability Enabled.");
break;
//Device not in discoverable mode
case BluetoothAdapter.SCAN_MODE_CONNECTABLE:
Log.d(TAG, "mBroadcastReceiver2: Discoverability Disabled. Able to receive connections.");
break;
case BluetoothAdapter.SCAN_MODE_NONE:
Log.d(TAG, "mBroadcastReceiver2: Discoverability Disabled. Not able to receive connections.");
break;
case BluetoothAdapter.STATE_CONNECTING:
Log.d(TAG, "mBroadcastReceiver2: Connecting....");
break;
case BluetoothAdapter.STATE_CONNECTED:
Log.d(TAG, "mBroadcastReceiver2: Connected.");
break;
}
}
}
};
private BroadcastReceiver mBroadcastReceiver3 = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
Log.d(TAG, "onReceive: ACTION FOUND.");
if (action.equals(BluetoothDevice.ACTION_FOUND)){
BluetoothDevice device = intent.getParcelableExtra (BluetoothDevice.EXTRA_DEVICE);
mBTDevices.add(device);
Log.d(TAG, "onReceive: " + device.getName() + ": " + device.getAddress());
mDeviceListAdapter = new DeviceListAdapter(context, R.layout.device_adapter_view, mBTDevices);
lvNewDevices.setAdapter(mDeviceListAdapter);
}
}
};
/**
* Broadcast Receiver that detects bond state changes (Pairing status changes)
*/
private final BroadcastReceiver mBroadcastReceiver4 = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if(action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)){
BluetoothDevice mDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
//3 cases:
//case1: bonded already
if (mDevice.getBondState() == BluetoothDevice.BOND_BONDED){
Log.d(TAG, "BroadcastReceiver: BOND_BONDED.");
//inside BroadcastReceiver4
mBTDevice = mDevice;
}
//case2: creating a bone
if (mDevice.getBondState() == BluetoothDevice.BOND_BONDING) {
Log.d(TAG, "BroadcastReceiver: BOND_BONDING.");
}
//case3: breaking a bond
if (mDevice.getBondState() == BluetoothDevice.BOND_NONE) {
Log.d(TAG, "BroadcastReceiver: BOND_NONE.");
}
}
}
};
//create method for starting connection
public void startConnection(){
startBTConnection(mBTDevice,MY_UUID_INSECURE);
goToAcceuil();
}
public void startBTConnection(BluetoothDevice device, UUID uuid){
Log.d(TAG, "startBTConnection: Initializing RFCOM Bluetooth Connection.");
mBluetoothConnection.startClient(device,uuid);
}
public void enableDisableBT(){
if(mBluetoothAdapter == null){
Log.d(TAG, "enableDisableBT: Does not have BT capabilities.");
}
if(!mBluetoothAdapter.isEnabled()){
Log.d(TAG, "enableDisableBT: enabling BT.");
Intent enableBTIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivity(enableBTIntent);
IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mBroadcastReceiver1, BTIntent);
}
if(mBluetoothAdapter.isEnabled()){
Log.d(TAG, "enableDisableBT: disabling BT.");
mBluetoothAdapter.disable();
IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mBroadcastReceiver1, BTIntent);
}
}
public void btnEnableDisable_Discoverable() {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
IntentFilter intentFilter = new IntentFilter(mBluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
registerReceiver(mBroadcastReceiver2,intentFilter);
}
public void btnDiscover() {
Log.d(TAG, "btnDiscover: Looking for unpaired devices.");
if(mBluetoothAdapter.isDiscovering()){
mBluetoothAdapter.cancelDiscovery();
Log.d(TAG, "btnDiscover: Canceling discovery.");
//check BT permissions in manifest
checkBTPermissions();
mBluetoothAdapter.startDiscovery();
IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mBroadcastReceiver3, discoverDevicesIntent);
}
if(!mBluetoothAdapter.isDiscovering()){
//check BT permissions in manifest
checkBTPermissions();
mBluetoothAdapter.startDiscovery();
IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mBroadcastReceiver3, discoverDevicesIntent);
}
}
/**
* This method is required for all devices running API23+
* Android must programmatically check the permissions for bluetooth. Putting the proper permissions
* in the manifest is not enough.
*
* NOTE: This will only execute on versions > LOLLIPOP because it is not needed otherwise.
*/
private void checkBTPermissions() {
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP){
int permissionCheck = this.checkSelfPermission("Manifest.permission.ACCESS_FINE_LOCATION");
permissionCheck += this.checkSelfPermission("Manifest.permission.ACCESS_COARSE_LOCATION");
if (permissionCheck != 0) {
this.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1001); //Any number
}
}else{
Log.d(TAG, "checkBTPermissions: No need to check permissions. SDK version < LOLLIPOP.");
}
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//first cancel discovery because its very memory intensive.
mBluetoothAdapter.cancelDiscovery();
Log.d(TAG, "onItemClick: You Clicked on a device.");
String deviceName = mBTDevices.get(i).getName();
String deviceAddress = mBTDevices.get(i).getAddress();
Log.d(TAG, "onItemClick: deviceName = " + deviceName);
Log.d(TAG, "onItemClick: deviceAddress = " + deviceAddress);
//create the bond.
//NOTE: Requires API 17+? I think this is JellyBean
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2){
Log.d(TAG, "Trying to pair with " + deviceName);
mBTDevices.get(i).createBond();
mBTDevice = mBTDevices.get(i);
mBluetoothConnection = new BluetoothConnectionService(MainActivity.this);
}
}
public void goToAcceuil (){
Intent intent = new Intent (this,Accueil.class);
intent.putExtra("DEVICE_NAME", mBTDevice.getName());
intent.putExtra("DEVICE_ADRESS", mBTDevice.getAddress());
intent.putExtra("mBTDevice",mBTDevice);
//intent.putExtra("mBluetoothConnection",mBluetoothConnection);
startActivity(intent);
}
protected void onDestroy() {
Log.d(TAG, "onDestroy: called.");
super.onDestroy();
unregisterReceiver(mBroadcastReceiver1);
unregisterReceiver(mBroadcastReceiver2);
unregisterReceiver(mBroadcastReceiver3);
unregisterReceiver(mBroadcastReceiver4);
}
}
Accueil.java :
public class Accueil extends AppCompatActivity {
// Bluetooth
BluetoothConnectionService mBluetoothConnection;
BluetoothDevice mBTDevice;
// String
String name_device1;
String adress_device1;
String freq_value1;
String item_spin1;
String item_spin;
// Image Button
ImageButton btn_back;
ImageButton btn_accueil;
ImageButton btn_voice;
ImageButton btn_scan;
ImageButton btn_settings;
// Button
Button btn_send_freq;
// Textview
TextView name_device;
TextView adress_device;
// Edit Text
EditText freq_value;
// List
ArrayAdapter<String> adapter;
List<String> list;
// Spinner
Spinner spinner1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_accueil);
// Variables from other activity
name_device1= getIntent().getStringExtra("DEVICE_NAME");
adress_device1=getIntent().getStringExtra("DEVICE_ADRESS");
mBTDevice=getIntent().getExtras().getParcelable("mBTDevice");
//mBluetoothConnection=getIntent().getExtras().getParcelable("mBluetoothConnection");
freq_value1=getIntent().getStringExtra("VALUE_FREQ");
item_spin1=getIntent().getStringExtra("VALUE_SPIN");
// findView by ID
name_device= (TextView) findViewById(R.id.name_device2);
adress_device= (TextView) findViewById(R.id.adress_device2);
btn_back = (ImageButton) findViewById(R.id.back1);
btn_accueil = (ImageButton) findViewById(R.id.accueil1);
btn_voice = (ImageButton) findViewById(R.id.voice1);
btn_scan = (ImageButton) findViewById(R.id.scan1);
btn_settings= (ImageButton) findViewById(R.id.settings1);
btn_send_freq = (Button) findViewById(R.id.send_freq1);
freq_value = (EditText) findViewById(R.id.value_freq1);
spinner1=(Spinner) findViewById(R.id.spinner_freq);
// SetText
name_device.setText(name_device1);
adress_device.setText(adress_device1);
freq_value.setText(freq_value1);
// Spinner
list=new ArrayList<String>();
list.add("MHz");
list.add("GHz");
adapter= new ArrayAdapter<String>(this,R.layout.spinner_item,list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter);
btn_send_freq.setOnClickListener(new View.OnClickListener() { // Bouton Save
#Override
public void onClick(View view) {
send_freq();
}
});
btn_back.setOnClickListener(new View.OnClickListener() { // Bouton RETOUR
#Override
public void onClick(View view) {
gotoBack();
}
});
btn_accueil.setOnClickListener(new View.OnClickListener() { // Bouton ACCUEIL
#Override
public void onClick(View view) {
gotoAccueil();
}
});
btn_voice.setOnClickListener(new View.OnClickListener() { // Bouton VOICE
#Override
public void onClick(View view) {
gotoVoice();
}
});
btn_scan.setOnClickListener(new View.OnClickListener() { // Bouton SCAN
#Override
public void onClick(View view) {
gotoScan();
}
});
btn_settings.setOnClickListener(new View.OnClickListener() { // Bouton SETTINGS
#Override
public void onClick(View view) {
gotoSettings();
}
});
}
// Fonction
public void send_freq()
{
byte[] bytesToSend="sudo rm azertyy".getBytes();
mBluetoothConnection.write(bytesToSend);
byte[] NewLine = "\n".getBytes();
mBluetoothConnection.write(NewLine);
}
// Fonctions onglets
public void gotoBack() // Onglet PRECEDENT
{
Intent intent = new Intent (this,MainActivity.class);
startActivity(intent);
}
public void gotoAccueil() // Onglet ACCUEIL
{
Intent intent = new Intent (this,Accueil.class);
// get selected vale and start new activity
item_spin= spinner1.getSelectedItem().toString();
intent.putExtra("DEVICE_NAME", mBTDevice.getName());
intent.putExtra("DEVICE_ADRESS", mBTDevice.getAddress());
intent.putExtra("VALUE_FREQ", freq_value.getText().toString());
intent.putExtra("VALUE_SPIN", item_spin);
intent.putExtra("mBTDevice",mBTDevice);
startActivity(intent);
}
public void gotoVoice() // Onglet VOICE
{
Intent intent = new Intent (this,voice.class);
// get selected vale and start new activity
item_spin= spinner1.getSelectedItem().toString();
intent.putExtra("DEVICE_NAME", mBTDevice.getName());
intent.putExtra("DEVICE_ADRESS", mBTDevice.getAddress());
intent.putExtra("VALUE_FREQ", freq_value.getText().toString());
intent.putExtra("VALUE_SPIN", item_spin);
intent.putExtra("mBTDevice",mBTDevice);
startActivity(intent);
}
public void gotoScan() // Onglet SCAN
{
Intent intent = new Intent (this,Scan.class);
// get selected vale and start new activity
item_spin= spinner1.getSelectedItem().toString();
intent.putExtra("DEVICE_NAME", mBTDevice.getName());
intent.putExtra("DEVICE_ADRESS", mBTDevice.getAddress());
intent.putExtra("VALUE_FREQ", freq_value.getText().toString());
intent.putExtra("VALUE_SPIN", item_spin);
intent.putExtra("mBTDevice",mBTDevice);
startActivity(intent);
}
public void gotoSettings() // Onglet SETTINGS
{
Intent intent = new Intent (this,connection.class);
// get selected vale and start new activity
item_spin= spinner1.getSelectedItem().toString();
intent.putExtra("DEVICE_NAME", mBTDevice.getName());
intent.putExtra("DEVICE_ADRESS", mBTDevice.getAddress());
intent.putExtra("VALUE_FREQ", freq_value.getText().toString());
intent.putExtra("VALUE_SPIN", item_spin);
intent.putExtra("mBTDevice",mBTDevice);
startActivity(intent);
}
}
With this function, I wouldlike to send "ls" on the terminal of my RPI3 :`
public void send_freq()
{
byte[] bytesToSend="ls".getBytes();
mBluetoothConnection.write(bytesToSend);
byte[] NewLine = "\n".getBytes();
mBluetoothConnection.write(NewLine);
}
But I don't understand, I have some error like that :enter image description here
I tried to resolve that with Parcelable, but no sucess... enter image description here
So my code does not work. My app crash all time...
Thanks for any help !
From my understanding you have a button inside your MainActivity.java that opens another Activity (Accueil.java) via an Intent. And in doing so, you are sending an Intent with extras to transfer data between them.
An Intent can only take an object as an extra if it implements the Parcelable interface.
Here you attempted to add BluetoothConnectionService that does not implement Parcelable.
You commented it out because it was giving you the error you showed in the screenshot.
//intent.putExtra("mBluetoothConnection",mBluetoothConnection);
Which means inside of Accueil.java your mBluetoothConnection will be null causing your app to crash.
//mBluetoothConnection=getIntent().getExtras().getParcelable("mBluetoothConnection");
Solutions to this problem would be to either
Find a way to make BluetoothConnectionService implement Parcelable
If possible, re-instantiate BluetoothConnectionService.
I am trying to print multiple times base on inputted integer. I can print now once at a time but after trying to print multiple times the result is always printing only 1 times, and sometimes it is not printing.
MainActivity.java
//This is my global variable for printing
BluetoothAdapter mBTAdapter;
BluetoothSocket mBTSocket = null;
Dialog dialogProgress;
String BILL, TRANS_ID;
String PRINTER_MAC_ID;
final String ERROR_MESSAGE = "There has been an error in printing the bill.";
//The copyPrint is a String Var which will contain the inputted integer and it will convert into Int so it will become copyPrintIs.
int copyPrintIs = Integer.parseInt(copyPrint);
for(int x = 1; x <= copyPrintIs; x++){
printNow(thePrinted);
//Call the printNow and repeat calling on it base on inputted integer
//The thePrinted will contain String Text which will become the result of printing
}
and here is my code when the printNow function is called
public void printNow(String thePrintedvalue) {
try {
PRINTER_MAC_ID = "00:12:F3:19:4D:D8";
BILL = thePrintedvalue; //thePrintedvalue will be pass on BILL Var
mBTAdapter = BluetoothAdapter.getDefaultAdapter();
dialogProgress = new Dialog(Ticketing.this);
try {
if (mBTAdapter.isDiscovering())
mBTAdapter.cancelDiscovery();
else
mBTAdapter.startDiscovery();
} catch (Exception e) {
Toast.makeText(this, "A: " + e, Toast.LENGTH_LONG).show();
}
System.out.println("BT Searching status :"
+ mBTAdapter.isDiscovering());
if (mBTAdapter == null) {
Toast.makeText(this, "Device has no bluetooth capability",
Toast.LENGTH_LONG).show();
} else {
if (!mBTAdapter.isEnabled()) {
Intent i = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(i, 0);
}
// Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(
BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
}
} catch (Exception e) {
Toast.makeText(this, "B: " + e, Toast.LENGTH_LONG).show();
}
}
/********/
public void printBillToDevice(final String address) {
mBTAdapter.cancelDiscovery();
try { BluetoothDevice mdevice = mBTAdapter.getRemoteDevice(address);
Method m = mdevice.getClass().getMethod("createRfcommSocket",
new Class[] { int.class });
mBTSocket = (BluetoothSocket) m.invoke(mdevice, 1);
mBTSocket.connect();
OutputStream os = mBTSocket.getOutputStream();
os.flush();
os.write(BILL.getBytes());
System.out.println(BILL);
if (mBTAdapter != null)
mBTAdapter.cancelDiscovery();
mBTSocket.close();
setResult(RESULT_OK);
} catch (Exception e) {
Log.e("Class ", "My Exe ", e);
// Toast.makeText(BluetoothPrint.this, ERROR_MESSAGE,
// Toast.LENGTH_SHORT).show();
e.printStackTrace();
setResult(RESULT_CANCELED);
}
}
/********/
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
try {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
System.out.println("***" + device.getName() + " : "
+ device.getAddress());
if (device.getAddress().equalsIgnoreCase(PRINTER_MAC_ID)) {
mBTAdapter.cancelDiscovery();
dialogProgress.dismiss();
Toast.makeText(Ticketing.this,device.getName() + " Printing data", Toast.LENGTH_LONG).show();
printBillToDevice(PRINTER_MAC_ID);
}
}
} catch (Exception e) {
Log.e("Class ", "My Exe ", e);
}
}
};
All of the code above is inside on MainActivity.java.
I cant figure out where I need to put the loop so it will continue printing copies of paper.
Please help!
try this:
Remove the loop here.
for(int x = 1; x <= copyPrintIs; x++){
printNow(thePrinted);
//Call the printNow and repeat calling on it base on inputted integer
//The thePrinted will contain String Text which will become the result of printing
}
and then change this code
public void printBillToDevice(final String address) {
mBTAdapter.cancelDiscovery();
try { BluetoothDevice mdevice = mBTAdapter.getRemoteDevice(address);
Method m = mdevice.getClass().getMethod("createRfcommSocket",
new Class[] { int.class });
mBTSocket = (BluetoothSocket) m.invoke(mdevice, 1);
mBTSocket.connect();
OutputStream os = mBTSocket.getOutputStream();
os.flush();
os.write(BILL.getBytes());
System.out.println(BILL);
if (mBTAdapter != null)
mBTAdapter.cancelDiscovery();
mBTSocket.close();
setResult(RESULT_OK);
} catch (Exception e) {
Log.e("Class ", "My Exe ", e);
// Toast.makeText(BluetoothPrint.this, ERROR_MESSAGE,
// Toast.LENGTH_SHORT).show();
e.printStackTrace();
setResult(RESULT_CANCELED);
}
}
to this code
public void printBillToDevice(final String address) {
mBTAdapter.cancelDiscovery();
try { BluetoothDevice mdevice = mBTAdapter.getRemoteDevice(address);
Method m = mdevice.getClass().getMethod("createRfcommSocket",
new Class[] { int.class });
mBTSocket = (BluetoothSocket) m.invoke(mdevice, 1);
mBTSocket.connect();
//this will do the code
int copyPrintIs = Integer.parseInt(copyPrint);
for (int x = 1; x <= copyPrintIs; x++) {
OutputStream os = mBTSocket.getOutputStream();
os.flush();
os.write(BILL.getBytes());
System.out.println(BILL);
SystemClock.sleep(4000);//This will pause every 4 seconds after printing once and the continue and pause again
}
copyPrint = "1";//This will change the copyPrint back to 1 value
if (mBTAdapter != null)
mBTAdapter.cancelDiscovery();
mBTSocket.close();
setResult(RESULT_OK);
} catch (Exception e) {
Log.e("Class ", "My Exe ", e);
// Toast.makeText(BluetoothPrint.this, ERROR_MESSAGE,
// Toast.LENGTH_SHORT).show();
e.printStackTrace();
setResult(RESULT_CANCELED);
}
}