I am beginner and making my first project on android studio. I want to exchange a unique string between devices over Bluetooth without pairing whenever devices are near. Following is the code I tried but did not work. The code I mention is of scanning part only when click on scan it search for the device and exchange the keys but it is not working.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ON = (Button) findViewById(R.id.button3);
OFF = (Button) findViewById(R.id.button5);
Scan = (Button) findViewById(R.id.search);
myBT = BluetoothAdapter.getDefaultAdapter();
Interaction = (Button) findViewById(R.id.intr);
intentON = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
other = (TextView)findViewById(R.id.textView4);
bluelist = (ListView) findViewById(R.id.btList);
//IntView = (ListView) findViewById(R.id.InList);
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
pAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
bluelist.setAdapter(arrayAdapter);
random = UUID.randomUUID();
getUUID = random.toString();
code = (TextView) findViewById(R.id.textView6);
data = getIntent().getExtras().getString("SomeNumbers");
code.setText(data);
send = (String) code.getText();
checkPermission();
ON.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(myBT.isEnabled())
Toast.makeText(getApplicationContext(), "Bluetooth already Enabled", Toast.LENGTH_SHORT).show();
else
bluetoothOn();
}
});
OFF.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
bluetoothOff();
}
});
Scan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
discover();
}
});
bluelist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//pairDevice(device);
}
});
Interaction.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent getInteractions = new Intent(MainActivity.this, Interactions.class);
//Bundle args = new Bundle();
//args.putSerializable("Exposure", (Serializable)arrayList);
getInteractions.putStringArrayListExtra("Exposure", arrayList);
startActivity(getInteractions);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == BLUETOOTH_REQ_CODE) {
if (resultCode == RESULT_OK) {
Toast.makeText(getApplicationContext(), "Bluetooth is Enabled", Toast.LENGTH_LONG).show();
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(getApplicationContext(), "Bluetooth Disabled", Toast.LENGTH_LONG).show();
}
}
}
private void discover(){
if(myBT.isDiscovering()){
myBT.cancelDiscovery();
Toast.makeText(getApplicationContext(),"Discovery stopped",Toast.LENGTH_SHORT).show();
}
else{
if(myBT.isEnabled()) {
arrayAdapter.clear(); // clear items
myBT.startDiscovery();
Toast.makeText(getApplicationContext(), "Discovery started", Toast.LENGTH_SHORT).show();
registerReceiver(receiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
}
else{
bluetoothOn();
}
}
}
private final BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)){
device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// add the name to the list
arrayAdapter.add(device.getName() + "\n" + device.getAddress());
arrayAdapter.notifyDataSetChanged();
ServerClass serverClass = new ServerClass();
serverClass.start();
ClientClass clientClass = new ClientClass(pairing);
clientClass.start();
sendReceive.write(send.getBytes());
}
}
};
Handler handler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(#NonNull Message msg) {
switch(msg.what)
{
case STATE_LISTENING:
Toast.makeText(getApplicationContext(), "Listening", Toast.LENGTH_SHORT).show();
break;
case STATE_CONNECTING:
Toast.makeText(getApplicationContext(), "Connecting", Toast.LENGTH_SHORT).show();
break;
case STATE_CONNECTED:
Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_SHORT).show();
break;
case STATE_CONNECTION_FAILED:
Toast.makeText(getApplicationContext(), "Connection Failed", Toast.LENGTH_SHORT).show();
break;
case STATE_MESSAGE_RECEIVED:
byte[] readBuff = (byte[]) msg.obj ;
String tempMsg = new String(readBuff,0,msg.arg1);
other.setText(tempMsg);
break;
}
return false;
}
});
private class ServerClass extends Thread
{
private BluetoothServerSocket serverSocket;
public ServerClass()
{
try {
serverSocket = myBT.listenUsingInsecureRfcommWithServiceRecord(App_Name,random);
} catch (IOException e) {
e.printStackTrace();
}
}
public void run()
{
BluetoothSocket socket=null;
while(socket == null)
{
try {
//Message msg = Message.obtain();
//msg.what=
//handler.sendMessage(msg);
socket=serverSocket.accept();
} catch (IOException e) {
e.printStackTrace();
//Message msg = Message.obtain();
//msg.what=
//handler.sendMessage(msg);
}
if(socket != null)
{
//Message msg = Message.obtain();
//msg.what=
//handler.sendMessage(msg);
sendReceive = new SendReceive(socket);
sendReceive.start();
break;
}
}
}
}
private class ClientClass extends Thread
{
private BluetoothDevice device;
private BluetoothSocket socket;
public ClientClass(BluetoothDevice device1)
{
device=device1;
try {
socket = device.createRfcommSocketToServiceRecord(random);
} catch (IOException e) {
e.printStackTrace();
}
}
public void run()
{
try {
socket.connect();
sendReceive = new SendReceive(socket);
sendReceive.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private class SendReceive extends Thread
{
private final BluetoothSocket bluetoothSocket;
private final InputStream inputStream;
private final OutputStream outputStream;
public SendReceive(BluetoothSocket socket)
{
bluetoothSocket=socket;
InputStream tempIn = null;
OutputStream tempOut = null;
try {
tempIn = bluetoothSocket.getInputStream();
tempOut = bluetoothSocket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
inputStream = tempIn;
outputStream = tempOut;
}
public void run()
{
byte[] buffer = new byte[1024];
int bytes;
while(true)
{
try {
bytes = inputStream.read(buffer);
handler.obtainMessage(STATE_MESSAGE_RECEIVED,bytes,-1,buffer).sendToTarget();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void write(byte[] bytes)
{
try {
outputStream.write(bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Related
I wanted to make bluetooth applications for arduino so that I could connect to the HC-05 module. And I found a tutorial on how to make a bluetooth connection (http://mcuhq.com/27/simple-android-bluetooth-application-with-arduino-example) When I downloaded the code from github, the application starts and everything works and connects. But the problem is that I can't open a new activity because the project is probably for 15 API and the new activity needs at least 16 so I decided to make such an application on my own based on the code from this website. And here I have a problem because when I make my phone search for bluetooth devices, nothing is displayed on my ListView.
This is my code `
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
offon = findViewById(R.id.BtBtn);
TV = findViewById(R.id.BtTv);
TV2 = findViewById(R.id.textView2);
TV3 = findViewById(R.id.bluetooth_status);
Next = findViewById(R.id.button2);
LV = findViewById(R.id.ListView);
disc = findViewById(R.id.button3);
ArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
adapter = BluetoothAdapter.getDefaultAdapter();
LV.setAdapter(ArrayAdapter);
LV.setOnItemClickListener(DeviceList);
handler = new Handler(Looper.getMainLooper()){
#Override
public void handleMessage(Message msg){
if(msg.what == MESSAGE_READ){
String readMessage = null;
readMessage = new String((byte[]) msg.obj, StandardCharsets.UTF_8);
TV2.setText(readMessage);
}
if(msg.what == CONNECTING_STATUS){
char[] sConnected;
if(msg.arg1 == 1)
TV3.setText(getString(R.string.BTConnected) + msg.obj);
else
TV3.setText(getString(R.string.BTconnFail));
}
}
};
if (adapter.isEnabled()){
TV.setText("Bluetooth ON");
}else TV.setText("Bluetooth OFF");
disc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
discovery();
if (!adapter.isEnabled()){
Toast.makeText(getBaseContext(), getString(R.string.BTnotOn), Toast.LENGTH_SHORT).show();
}
}
});
offon.setOnClickListener(new View.OnClickListener() {
#SuppressLint("MissingPermission")
#Override
public void onClick(View view) {
if (adapter.isEnabled()) {
adapter.disable();
TV.setText("Bluetooth OFF");
}else {
adapter.enable();
TV.setText("Bluetooth ON");
}
}
});
Next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
open2activity();
}
});
}
public void open2activity(){
Intent intent = new Intent(this, MainActivity2.class);
startActivity(intent);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent Data) {
super.onActivityResult(requestCode, resultCode, Data);
}
#SuppressLint("MissingPermission")
private void discovery(){
if (adapter.isDiscovering()){
adapter.cancelDiscovery();
Toast.makeText(getApplicationContext(), getString(R.string.DisStop), Toast.LENGTH_SHORT).show();
}
else{
if (adapter.isEnabled()){
ArrayAdapter.clear();
adapter.startDiscovery();
Toast.makeText(getApplicationContext(), getString(R.string.DisStart), Toast.LENGTH_SHORT).show();
registerReceiver(blReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
}
}
}
final BroadcastReceiver blReceiver = new BroadcastReceiver() {
#SuppressLint("MissingPermission")
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)){
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
ArrayAdapter.add(device.getName() + "\n" + device.getAddress());
ArrayAdapter.notifyDataSetChanged();
}
}
};
private AdapterView.OnItemClickListener DeviceList = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TV3.setText(getString(R.string.cConnet));
String info = ((TextView)view).getText().toString();
final String address = info.substring(info.length() - 17);
final String name = info.substring(0,info.length() - 17);
new Thread()
{
#SuppressLint("MissingPermission")
#Override
public void run() {
boolean fail = false;
BluetoothDevice device = adapter.getRemoteDevice(address);
try {
BTSocket = createBluetoothSocket(device);
} catch (IOException e) {
fail = true;
Toast.makeText(getBaseContext(), getString(R.string.ErrSockCrea), Toast.LENGTH_SHORT).show();
}
try {
BTSocket.connect();
} catch (IOException e) {
try {
fail = true;
BTSocket.close();
handler.obtainMessage(CONNECTING_STATUS, -1, -1)
.sendToTarget();
} catch (IOException e2) {
Toast.makeText(getBaseContext(), getString(ErrSockCrea), Toast.LENGTH_SHORT).show();
}
}
if(!fail) {
ConnectedThread = new ConnectedThread(BTSocket, handler);
ConnectedThread.start();
handler.obtainMessage(CONNECTING_STATUS, 1, -1, name)
.sendToTarget();
}
}
}.start();
}
};
#SuppressLint("MissingPermission")
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
try {
final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", UUID.class);
return (BluetoothSocket) m.invoke(device, BT_MODULE_UUID);
} catch (Exception e) {
Log.e(TAG, "Could not create Insecure RFComm Connection",e);
}
return device.createRfcommSocketToServiceRecord(BT_MODULE_UUID);
}
}
`
I tried to do as above but nothing is displayed
Im trying develop Bluetooth chat application.
When I am trying connect another device via Bluetooth getting below error :
2020-08-20 22:54:28.501 3710-3729/com..btconnection I/OpenGLRenderer: Initialized EGL, version 1.4
2020-08-20 22:54:28.501 3710-3729/com.test.btconnection D/OpenGLRenderer: Swap behavior 1
2020-08-20 22:54:31.736 3710-3710/com.test.btconnection V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance#ae9591c
2020-08-20 22:54:32.141 3710-3710/com.test.btconnection W/IInputConnectionWrapper: finishComposingText on inactive InputConnection
2020-08-20 22:54:38.014 3710-3849/com.test.btconnection W/BluetoothAdapter: getBluetoothService() called with no BluetoothManagerCallback
2020-08-20 22:54:38.040 3710-3710/com.test.btconnection W/InputEventReceiver: Attempted to finish an input event but the input event receiver has already been disposed.
2020-08-20 22:54:40.868 3710-3710/com.test.btconnection I/Toast: Show toast from OpPackageName:com.test.btconnection, PackageName:com.test.btconnection
MainActivity.java
public class MainActivity extends AppCompatActivity {
private TextView status;
private Button btnConnect;
private ListView listView;
private Dialog dialog;
private TextInputLayout inputLayout;
private ArrayAdapter<String> chatAdapter;
private ArrayList<String> chatMessages;
private BluetoothAdapter bluetoothAdapter;
public static final int MESSAGE_STATE_CHANGE = 1;
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_WRITE = 3;
public static final int MESSAGE_DEVICE_OBJECT = 4;
public static final int MESSAGE_TOAST = 5;
public static final String DEVICE_OBJECT = "device_name";
private static final int REQUEST_ENABLE_BLUETOOTH = 1;
private ChatController chatController;
private BluetoothDevice connectingDevice;
private ArrayAdapter<String> discoveredDevicesAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main1);
findViewsByIds();
//check device support bluetooth or not
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not available!", Toast.LENGTH_SHORT).show();
finish();
}
//show bluetooth devices dialog when click connect button
btnConnect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showPrinterPickDialog();
}
});
//set chat adapter
chatMessages = new ArrayList<>();
chatAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, chatMessages);
listView.setAdapter(chatAdapter);
}
private Handler handler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_STATE_CHANGE:
switch (msg.arg1) {
case ChatController.STATE_CONNECTED:
setStatus("Connected to: " + connectingDevice.getName());
btnConnect.setEnabled(false);
break;
case ChatController.STATE_CONNECTING:
setStatus("Connecting...");
btnConnect.setEnabled(false);
break;
case ChatController.STATE_LISTEN:
case ChatController.STATE_NONE:
setStatus("Not connected");
break;
}
break;
case MESSAGE_WRITE:
byte[] writeBuf = (byte[]) msg.obj;
String writeMessage = new String(writeBuf);
chatMessages.add("Me: " + writeMessage);
chatAdapter.notifyDataSetChanged();
break;
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
String readMessage = new String(readBuf, 0, msg.arg1);
chatMessages.add(connectingDevice.getName() + ": " + readMessage);
chatAdapter.notifyDataSetChanged();
break;
case MESSAGE_DEVICE_OBJECT:
connectingDevice = msg.getData().getParcelable(DEVICE_OBJECT);
Toast.makeText(getApplicationContext(), "Connected to " + connectingDevice.getName(),
Toast.LENGTH_SHORT).show();
break;
case MESSAGE_TOAST:
Toast.makeText(getApplicationContext(), msg.getData().getString("toast"),
Toast.LENGTH_SHORT).show();
break;
}
return false;
}
});
private void showPrinterPickDialog() {
dialog = new Dialog(this);
dialog.setContentView(R.layout.layout_bluetooth);
dialog.setTitle("Bluetooth Devices");
if (bluetoothAdapter.isDiscovering()) {
bluetoothAdapter.cancelDiscovery();
}
bluetoothAdapter.startDiscovery();
//Initializing bluetooth adapters
ArrayAdapter<String> pairedDevicesAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
discoveredDevicesAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
//locate listviews and attatch the adapters
ListView listView = (ListView) dialog.findViewById(R.id.pairedDeviceList);
ListView listView2 = (ListView) dialog.findViewById(R.id.discoveredDeviceList);
listView.setAdapter(pairedDevicesAdapter);
listView2.setAdapter(discoveredDevicesAdapter);
// Register for broadcasts when a device is discovered
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(discoveryFinishReceiver, filter);
// Register for broadcasts when discovery has finished
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(discoveryFinishReceiver, filter);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
// If there are paired devices, add each one to the ArrayAdapter
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
pairedDevicesAdapter.add(device.getName() + "\n" + device.getAddress());
}
} else {
pairedDevicesAdapter.add(getString(R.string.none_paired));
}
//Handling listview item click event
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
bluetoothAdapter.cancelDiscovery();
String info = ((TextView) view).getText().toString();
String address = info.substring(info.length() - 17);
connectToDevice(address);
dialog.dismiss();
}
});
listView2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
bluetoothAdapter.cancelDiscovery();
String info = ((TextView) view).getText().toString();
String address = info.substring(info.length() - 17);
connectToDevice(address);
dialog.dismiss();
}
});
dialog.findViewById(R.id.cancelButton).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.setCancelable(false);
dialog.show();
}
private void setStatus(String s) {
status.setText(s);
}
private void connectToDevice(String deviceAddress) {
bluetoothAdapter.cancelDiscovery();
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress);
chatController.connect(device);
}
private void findViewsByIds() {
status = (TextView) findViewById(R.id.status);
btnConnect = (Button) findViewById(R.id.btn_connect);
listView = (ListView) findViewById(R.id.list);
inputLayout = (TextInputLayout) findViewById(R.id.input_layout);
View btnSend = findViewById(R.id.btn_send);
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (inputLayout.getEditText().getText().toString().equals("")) {
Toast.makeText(MainActivity.this, "Please input some texts", Toast.LENGTH_SHORT).show();
} else {
//TODO: here
sendMessage(inputLayout.getEditText().getText().toString());
inputLayout.getEditText().setText("");
}
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_ENABLE_BLUETOOTH:
if (resultCode == Activity.RESULT_OK) {
chatController = new ChatController(this, handler);
} else {
Toast.makeText(this, "Bluetooth still disabled, turn off application!", Toast.LENGTH_SHORT).show();
finish();
}
}
}
private void sendMessage(String message) {
if (chatController.getState() != ChatController.STATE_CONNECTED) {
Toast.makeText(this, "Connection was lost!", Toast.LENGTH_SHORT).show();
return;
}
if (message.length() > 0) {
byte[] send = message.getBytes();
chatController.write(send);
}
}
#Override
public void onStart() {
super.onStart();
if (!bluetoothAdapter.isEnabled()) {
android.content.Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BLUETOOTH);
} else {
chatController = new ChatController(this, handler);
}
}
#Override
public void onResume() {
super.onResume();
if (chatController != null) {
if (chatController.getState() == ChatController.STATE_NONE) {
chatController.start();
}
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (chatController != null)
chatController.stop();
}
private final BroadcastReceiver discoveryFinishReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
discoveredDevicesAdapter.add(device.getName() + "\n" + device.getAddress());
}
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
if (discoveredDevicesAdapter.getCount() == 0) {
discoveredDevicesAdapter.add(getString(R.string.none_found));
}
}
}
};
}
ChatController.java
public class ChatController {
private static final String APP_NAME = "BluetoothChatApp";
private static final UUID MY_UUID = UUID.fromString("8ce255c0-200a-11e0-ac64-0800200c9a66");
private final BluetoothAdapter bluetoothAdapter;
private final Handler handler;
private AcceptThread acceptThread;
private ConnectThread connectThread;
private ReadWriteThread connectedThread;
private int state;
static final int STATE_NONE = 0;
static final int STATE_LISTEN = 1;
static final int STATE_CONNECTING = 2;
static final int STATE_CONNECTED = 3;
public ChatController(Context context, Handler handler) {
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
state = STATE_NONE;
this.handler = handler;
}
// Set the current state of the chat connection
private synchronized void setState(int state) {
this.state = state;
handler.obtainMessage(MainActivity.MESSAGE_STATE_CHANGE, state, -1).sendToTarget();
}
// get current connection state
public synchronized int getState() {
return state;
}
// start service
public synchronized void start() {
// Cancel any thread
if (connectThread != null) {
connectThread.cancel();
connectThread = null;
}
// Cancel any running thresd
if (connectedThread != null) {
connectedThread.cancel();
connectedThread = null;
}
setState(STATE_LISTEN);
if (acceptThread == null) {
acceptThread = new AcceptThread();
acceptThread.start();
}
}
// initiate connection to remote device
public synchronized void connect(BluetoothDevice device) {
// Cancel any thread
if (state == STATE_CONNECTING) {
if (connectThread != null) {
connectThread.cancel();
connectThread = null;
}
}
// Cancel running thread
if (connectedThread != null) {
connectedThread.cancel();
connectedThread = null;
}
// Start the thread to connect with the given device
connectThread = new ConnectThread(device);
connectThread.start();
setState(STATE_CONNECTING);
}
// manage Bluetooth connection
public synchronized void connected(BluetoothSocket socket, BluetoothDevice device) {
// Cancel the thread
if (connectThread != null) {
connectThread.cancel();
connectThread = null;
}
// Cancel running thread
if (connectedThread != null) {
connectedThread.cancel();
connectedThread = null;
}
if (acceptThread != null) {
acceptThread.cancel();
acceptThread = null;
}
// Start the thread to manage the connection and perform transmissions
connectedThread = new ReadWriteThread(socket);
connectedThread.start();
// Send the name of the connected device back to the UI Activity
Message msg = handler.obtainMessage(MainActivity.MESSAGE_DEVICE_OBJECT);
Bundle bundle = new Bundle();
bundle.putParcelable(MainActivity.DEVICE_OBJECT, device);
msg.setData(bundle);
handler.sendMessage(msg);
setState(STATE_CONNECTED);
}
// stop all threads
public synchronized void stop() {
if (connectThread != null) {
connectThread.cancel();
connectThread = null;
}
if (connectedThread != null) {
connectedThread.cancel();
connectedThread = null;
}
if (acceptThread != null) {
acceptThread.cancel();
acceptThread = null;
}
setState(STATE_NONE);
}
public void write(byte[] out) {
ReadWriteThread r;
synchronized (this) {
if (state != STATE_CONNECTED)
return;
r = connectedThread;
}
r.write(out);
}
private void connectionFailed() {
Message msg = handler.obtainMessage(MainActivity.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString("toast", "Unable to connect device");
msg.setData(bundle);
handler.sendMessage(msg);
// Start the service over to restart listening mode
ChatController.this.start();
}
private void connectionLost() {
Message msg = handler.obtainMessage(MainActivity.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString("toast", "Device connection was lost");
msg.setData(bundle);
handler.sendMessage(msg);
// Start the service over to restart listening mode
ChatController.this.start();
}
// runs while listening for incoming connections
private class AcceptThread extends Thread {
private final BluetoothServerSocket serverSocket;
public AcceptThread() {
BluetoothServerSocket tmp = null;
try {
tmp = bluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord(APP_NAME, MY_UUID);
} catch (IOException ex) {
ex.printStackTrace();
}
serverSocket = tmp;
}
public void run() {
setName("AcceptThread");
BluetoothSocket socket;
while (state != STATE_CONNECTED) {
try {
socket = serverSocket.accept();
} catch (IOException e) {
break;
}
// If a connection was accepted
if (socket != null) {
synchronized (ChatController.this) {
switch (state) {
case STATE_LISTEN:
case STATE_CONNECTING:
// start the connected thread.
connected(socket, socket.getRemoteDevice());
break;
case STATE_NONE:
case STATE_CONNECTED:
// Either not ready or already connected. Terminate
// new socket.
try {
socket.close();
} catch (IOException e) {
}
break;
}
}
}
}
}
public void cancel() {
try {
serverSocket.close();
} catch (IOException e) {
}
}
}
// runs while attempting to make an outgoing connection
private class ConnectThread extends Thread {
private final BluetoothSocket socket;
private final BluetoothDevice device;
public ConnectThread(BluetoothDevice device) {
this.device = device;
BluetoothSocket tmp = null;
try {
tmp = device.createInsecureRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
e.printStackTrace();
}
socket = tmp;
}
public void run() {
setName("ConnectThread");
// Always cancel discovery because it will slow down a connection
bluetoothAdapter.cancelDiscovery();
// Make a connection to the BluetoothSocket
try {
socket.connect();
} catch (IOException e) {
try {
socket.close();
} catch (IOException e2) {
}
connectionFailed();
return;
}
// Reset the ConnectThread because we're done
synchronized (ChatController.this) {
connectThread = null;
}
// Start the connected thread
connected(socket, device);
}
public void cancel() {
try {
socket.close();
} catch (IOException e) {
}
}
}
// runs during a connection with a remote device
private class ReadWriteThread extends Thread {
private final BluetoothSocket bluetoothSocket;
private final InputStream inputStream;
private final OutputStream outputStream;
public ReadWriteThread(BluetoothSocket socket) {
this.bluetoothSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
}
inputStream = tmpIn;
outputStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[1024];
int bytes;
// Keep listening to the InputStream
while (true) {
try {
// Read from the InputStream
bytes = inputStream.read(buffer);
// Send the obtained bytes to the UI Activity
handler.obtainMessage(MainActivity.MESSAGE_READ, bytes, -1,
buffer).sendToTarget();
} catch (IOException e) {
connectionLost();
// Start the service over to restart listening mode
ChatController.this.start();
break;
}
}
}
// write to OutputStream
public void write(byte[] buffer) {
try {
outputStream.write(buffer);
handler.obtainMessage(MainActivity.MESSAGE_WRITE, -1, -1,
buffer).sendToTarget();
} catch (IOException e) {
}
}
public void cancel() {
try {
bluetoothSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Can you please me to resolve this error.
I have followed this link (getbluetoothservice() called with no bluetoothmanagercallback). I could not understand.
Issue is resolved after changing the UUID.
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
I'm trying to recieve/send data to arduino board using bluetooth, and I can connect to board from one activity. I know that I can make my other activities connect with bluetooth using service but I don't know how to make bluetooth as service. and i don't know how to send and recieve from it.
my Paired Devices code:
public class BTConnect extends AppCompatActivity {
private static final String TAG = "BTConnect";
ListView IdLista;
public static String EXTRA_DEVICE_ADDRESS = "device_address";
private BluetoothAdapter mBtAdapter;
private ArrayAdapter<String> mPairedDevicesArrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_btconnect);
}
#Override
public void onResume()
{
super.onResume();
//---------------------------------
VerificarEstadoBT();
//
mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.btconnect_nombre);
IdLista = (ListView)findViewById(R.id.Id2);
IdLista.setAdapter(mPairedDevicesArrayAdapter);
IdLista.setOnItemClickListener(mDeviceClickListener);
mBtAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();
if (pairedDevices.size() > 0)
{
for (BluetoothDevice device: pairedDevices) {
mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
}
}
private AdapterView.OnItemClickListener mDeviceClickListener = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView av, View v, int arg2, long arg3) {
String info = ((TextView) v).getText().toString();
String address = info.substring(info.length() - 17);
Intent i = new Intent(BTConnect.this, device.class);
i.putExtra(EXTRA_DEVICE_ADDRESS, address);
startActivity(i);
}
};
private void VerificarEstadoBT() {
mBtAdapter= BluetoothAdapter.getDefaultAdapter();
if(mBtAdapter==null) {
Toast.makeText(getBaseContext(), "the device can't connect to BT", Toast.LENGTH_SHORT).show();
} else {
if (mBtAdapter.isEnabled()) {
Log.d(TAG, "...Bluetooth Activation...");
} else {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
}}
And my first activity 'device' :
public class device extends AppCompatActivity {
Button IdEncender, IdApagar,IdDesconectar,IdReset;
ArrayList<String> addArray = new ArrayList<String>();
ListView show;
//-------------------------------------------
Handler bluetoothIn;
final int handlerState = 0;
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private StringBuilder DataStringIN = new StringBuilder();
private ConnectedThread MyConexionBT;
// Identificador unico de servicio - SPP UUID
private static final UUID BTMODULEUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// String para la direccion MAC
private static String address = null;
//-------------------------------------------
#SuppressLint("HandlerLeak")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_device);
IdEncender = (Button) findViewById(R.id.IdEncender);
IdApagar = (Button) findViewById(R.id.IdApagar);
IdDesconectar = (Button) findViewById(R.id.IdDisconectar);
show = (ListView) findViewById(R.id.LIST1) ;
IdReset=(Button)findViewById(R.id.IdReset);
bluetoothIn = new Handler() {
public void handleMessage(android.os.Message msg) {
if (msg.what == handlerState) {
String readMessage = (String) msg.obj;
DataStringIN.append(readMessage);
int endOfLineIndex = DataStringIN.indexOf("#");
if (endOfLineIndex > 0) {
String dataInPrint = DataStringIN.substring(0, endOfLineIndex);
String newline = "\r\n";
DataStringIN.delete(0, DataStringIN.length());
//--List adapter--//
addArray.add(dataInPrint);
ArrayAdapter<String> adapter =new ArrayAdapter<String>(device.this, android.R.layout.simple_list_item_1, addArray);
show.setAdapter(adapter);
}
}
};
btAdapter = BluetoothAdapter.getDefaultAdapter(); // get Bluetooth adapter
VerificarEstadoBT();
IdEncender.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
MyConexionBT.write("1");
}
});
IdApagar.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
MyConexionBT.write("0");
}
});
IdDesconectar.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (btSocket!=null)
{
try {btSocket.close();}
catch (IOException e)
{ Toast.makeText(getBaseContext(), "Error", Toast.LENGTH_SHORT).show();;}
}
finish();
}
});
configurebutton();
}
private void configurebutton() {
Button startbutton = (Button)findViewById(R.id.Start);
startbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(device.this,chart.class));
}
});
}
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException
{
return device.createRfcommSocketToServiceRecord(BTMODULEUUID);
}
#Override
public void onResume()
{
super.onResume();
Intent intent = getIntent();
address = intent.getStringExtra(BTConnect.EXTRA_DEVICE_ADDRESS);
BluetoothDevice device = btAdapter.getRemoteDevice(address);
try
{
btSocket = createBluetoothSocket(device);
} catch (IOException e) {
Toast.makeText(getBaseContext(), "fail", Toast.LENGTH_LONG).show();
}
try
{
btSocket.connect();
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {}
}
MyConexionBT = new ConnectedThread(btSocket);
MyConexionBT.start();
}
#Override
public void onPause()
{
super.onPause();
try
{
btSocket.close();
} catch (IOException e2) {}
}
private void VerificarEstadoBT() {
if(btAdapter==null) {
Toast.makeText(getBaseContext(), "error in bluetooth connection", Toast.LENGTH_LONG).show();
} else {
if (btAdapter.isEnabled()) {
} else {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
}
public void savefile(String file, String text){
try {
FileOutputStream fos = openFileOutput(file, Context.MODE_APPEND);
fos.write(text.getBytes());
fos.close();
Toast.makeText(device.this, "saved!", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(device.this,"error",Toast.LENGTH_LONG).show();
}
}
//Crea la clase que permite crear el evento de conexion
private class ConnectedThread extends Thread
{
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket)
{
InputStream tmpIn = null;
OutputStream tmpOut = null;
try
{
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run()
{
byte[] buffer = new byte[256];
int bytes;
while (true) {
try {
bytes = mmInStream.read(buffer);
String readMessage = new String(buffer, 0, bytes);
bluetoothIn.obtainMessage(handlerState, bytes, -1, readMessage).sendToTarget();
} catch (IOException e) {
break;
}
}
}
public void write(String input)
{
try {
mmOutStream.write(input.getBytes());
}
catch (IOException e)
{
Toast.makeText(getBaseContext(), "fail to connect", Toast.LENGTH_LONG).show();
finish();
}
}
}
}
If shortly move your connection/message_exchange logic to Thread/Runnable and start it from Service. You can exchange data between Service and Activity/Activities with BroadcastReceivers or Messenger. I also recommend you to use Bluetooth lib:
implementation 'me.aflak.libraries:bluetooth:1.3.4' this one already have inside thread so it is become easy to embed in your service.
Example code of service which use this lib and Messenger:
private ArrayList<Messenger> mClients = new ArrayList<>();
final private Messenger inComingMessenger = new Messenger(mIncomingHandler);
#SuppressLint("HandlerLeak")
final Handler mIncomingHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case Constants.MSG_REGISTER_CLIENT:
mClients.add(msg.replyTo);
Log.d(TAG, "handleMessage: new client connected. Total: " + mClients.size());
break;
case Constants.MSG_UNREGISTER_CLIENT:
mClients.remove(msg.replyTo);
Log.d(TAG, "handleMessage: client disconnected. Total: " + mClients.size());
break;
case Constants.MSG_YOUR_MESSAGE_TYPE:
String val = (String) msg.obj;
// stuff to do
break;
}
}
};
/**
* Send message to connected activities
*/
public void sendMessageToClients(int msgSignal, Object obj) {
if (mClients.size() == 0)
return;
sendMessage(mClients.get(0), Message.obtain(null, msgSignal, obj));
for (int i = 1; i < mClients.size(); i++) {
if (mClients.get(i) == null)
continue;
sendMessage(mClients.get(i), Message.obtain(null, msgSignal, obj));
}
}
/**
* Send message to binded activity
*/
private void sendMessage(Messenger msgr, Message msg) {
try {
msgr.send((msg));
} catch (RemoteException e) {
Log.e(TAG, "can't send message", e);
e.printStackTrace();
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
Log.d(TAG, "onStartCommand");
return START_STICKY;
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
Log.d(TAG, "onBind");
return inComingMessenger.getBinder();
}
#Override
public void onCreate() {
super.onCreate();
bleDevices = new ArrayList<>();
if(bluetooth == null) {
bluetooth = new Bluetooth(this);
bluetooth.setBluetoothCallback(new BluetoothCallback() {
#Override
public void onBluetoothTurningOn() {}
#Override
public void onBluetoothOn() {}
#Override
public void onBluetoothTurningOff() {
bluetooth = null;
}
#Override
public void onBluetoothOff() { }
#Override
public void onUserDeniedActivation() {
// when using bluetooth.showEnableDialog()
// you will also have to call bluetooth.onActivityResult()
}
});
bluetooth.setDiscoveryCallback(new DiscoveryCallback() {
#Override public void onDiscoveryStarted() {
}
#Override public void onDiscoveryFinished() {
bleDevices.clear();
}
#Override public void onDeviceFound(BluetoothDevice device) {
if(bleDevices.indexOf(device)<0) {
bleDevices.add(device);
Log.d(TAG, "Found new device while scanning: "+device.getAddress());
sendMessageToClients(Constants.MSG_BLE_DEVICE_FOUND, device);
}
}
#Override public void onDevicePaired(BluetoothDevice device) {}
#Override public void onDeviceUnpaired(BluetoothDevice device) {}
#Override public void onError(String message) {
Log.e(TAG, "DiscoveryCallback onError "+message);
}
});
bluetooth.setDeviceCallback(new DeviceCallback() {
#Override public void onDeviceConnected(BluetoothDevice device) { }
#Override public void onDeviceDisconnected(BluetoothDevice device, String message) { }
#Override public void onMessage(String message) {
// Handle your message
yourHandleFunction(message.replaceAll(" ",""));
Log.d(TAG, message);
}
#Override public void onError(String message) {
Log.e(TAG, "DeviceCallback onError "+message);
}
#Override public void onConnectError(BluetoothDevice device, String message) { }
});
bluetooth.onStart();
}
connectToSavedDevice();
}
}
private void connectToSavedDevice() {
Log.d(TAG, "connectToSavedDevice state="+getState());
if(getState() != STATE_DISCONNECTED) return;
SharedPreferences pref = getSharedPreferences(App.TAG, 0);
String address = pref.getString(Constants.PREF_AUTO_CONNECT_TO_ADDRESS, null);
if(address == null) {
Log.d(TAG, "saved address==null start scan for devices");
scanDevices();
return;
}
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(address);
if(device!=null) {
Log.d(TAG, "device found try to connect/bound, connect to Arduino");
bluetooth.connectToAddress(address,false);
}
}
In activity implement ServiceConnection interface:
protected synchronized void unbindService() {
if (!isBound()) {
return;
}
// lock object (prevents access to service while disconnecting)
synchronized (outComingMessenger) {
sendMessageToService(Message.obtain(null, Constants.MSG_UNREGISTER_CLIENT));
unbindService(this);
outComingMessenger = null;
}
}
protected void bindService() {
bindService(mServiceIntent, this, BIND_AUTO_CREATE);
}
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
outComingMessenger = new Messenger(service);
final Message msg = Message.obtain(null, Constants.MSG_REGISTER_CLIENT);
msg.replyTo = inComingMessenger;
msg.obj = getClass().getSimpleName();
sendMessageToService(msg);
sendMessageToService(Constants.MSG_CHECK_IS_CONNECTION_READY);
}
#Override
public void onServiceDisconnected(ComponentName name) {
outComingMessenger = null;
bindService();
}
/**
* Send message to service
*/
protected void sendMessageToService(Message msg) {
if (!isBound()) {
return;
}
try {
msg.replyTo = inComingMessenger;
outComingMessenger.send(msg);
} catch (RemoteException e) {
}
}
/**
* Send simple message to connected service
* #param messageId
*/
protected void sendMessageToService(int messageId) {
sendMessageToService(Message.obtain(null, messageId));
}
/**
* Send simple message to connected service
* #param messageId
*/
protected void sendMessageToService(int messageId, Object obj) {
sendMessageToService(Message.obtain(null, messageId, obj));
}
/**
* Service is connected?
*/
protected final boolean isBound() {
return outComingMessenger != null;
}
#SuppressLint("HandlerLeak")
private final Handler mIncomingHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case Constants.MSG_YOUR_MESSAGE:
int res = (int) msg.obj;
break;
case Constants.MSG_CONNECTION_READY:
isReady = (boolean) msg.obj;
if(isReady) {
// show toast or what you want to do with the UI
} else {
// do something else
}
break;
case Constants.MSG_BLE_DEVICE_FOUND:
BluetoothDevice device = (BluetoothDevice)msg.obj;
SharedPreferences pref = getSharedPreferences(App.TAG, 0);
String deviceAddress = pref.getString(Constants.PREF_AUTO_CONNECT_TO_ADDRESS, null);
break;
}
}
};
final private Messenger inComingMessenger = new Messenger(mIncomingHandler);
I wanted to start with the basics of bluetooth connection and make a simple app capable of scanning, pairing and connecting.
I'm struggling with the last concept, i followed a lot of tutorials but I couldn't make it. I don't know if you can help me but here is my code.
ublic class MainActivity extends Activity {
private final String TAG = "Debugging";
private final static int REQUEST_CODE_ENABLE_BLUETOOTH = 0;
protected static final int SUCCESS_CONNECT = 0;
protected static final int MESSAGE_READ = 1;
public static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
BluetoothAdapter btAdapter;
ArrayList<String> arrayListpaired;
ArrayAdapter<String> listAdapter,adapter;
ListView listView,listViewPaired;
Set<BluetoothDevice> deviceArray;
ArrayList<String> pairedDevices;
IntentFilter filter;
BroadcastReceiver receiver;
BluetoothDevice bdDevice;
ArrayList<BluetoothDevice> arrayListBluetoothDevices = null;
ArrayList<BluetoothDevice> arrayListPairedBluetoothDevices;
ListItemClicked listItemClicked;
ListItemClickedonPaired listItemClickedonPaired;
String tag = "debugging";
Handler mHandler= new Handler() {
public void handleMessage(Message msg){
super.handleMessage(msg);
switch(msg.what){
case SUCCESS_CONNECT:
ConnectedThread connectedThread = new ConnectedThread((BluetoothSocket)msg.obj);
Toast.makeText(getApplicationContext(),"Connect",Toast.LENGTH_LONG).show();
String s= "Succesfully connected";
connectedThread.write(s.getBytes());
Log.i(tag, "connected");
break;
case MESSAGE_READ:
byte[] readbuff=(byte[])msg.obj;
String string= readbuff.toString();
Toast.makeText(getApplicationContext(), string,Toast.LENGTH_SHORT).show();
break;
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btAdapter = BluetoothAdapter.getDefaultAdapter();
arrayListBluetoothDevices = new ArrayList<BluetoothDevice>();
arrayListpaired = new ArrayList<String>();
arrayListPairedBluetoothDevices = new ArrayList<BluetoothDevice>();
adapter= new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, arrayListpaired);
listItemClickedonPaired = new ListItemClickedonPaired();
listViewPaired = (ListView) findViewById(R.id.listView3);
listItemClicked = new ListItemClicked();
listView = (ListView) findViewById(R.id.listView2);
listAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_activated_1);
listView.setAdapter(listAdapter);
listAdapter.notifyDataSetChanged();
listViewPaired.setAdapter(adapter);
setupMessageButton1();
setupMessageButton2();
setupMessageButton3();
setupMessageButton4();
setupMessageButton5();
init();
getPairedDevices();
}
private void init() {
listView.setOnItemClickListener(listItemClicked);
listViewPaired.setOnItemClickListener(listItemClickedonPaired);
filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String Action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(Action)) {
Toast.makeText(getApplicationContext(), "One Device Found", Toast.LENGTH_SHORT).show();
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (arrayListBluetoothDevices.size() < 1) // this checks if the size of bluetooth device is 0,then add the
{ // device to the arraylist.
listAdapter.add(device.getName() + "\n" + device.getAddress());
arrayListBluetoothDevices.add(device);
listAdapter.notifyDataSetChanged();
}
else
{
boolean flag = true; // flag to indicate that particular device is already in the arlist or not
for (int i = 0; i < arrayListBluetoothDevices.size(); i++) {
if (device.getAddress().equals(arrayListBluetoothDevices.get(i).getAddress())) {
flag = false;
}
}
if (flag == true) {
listAdapter.add(device.getName() + "\n" + device.getAddress());
arrayListBluetoothDevices.add(device);
listAdapter.notifyDataSetChanged();
}
}
}
}
};
registerReceiver(receiver, filter);
}
private void createBond(BluetoothDevice btDevice){
try
{
Method method = btDevice.getClass().getMethod("createBond", (Class[]) null);
method.invoke(btDevice, (Object[]) null);
}
catch (Exception e)
{
e.printStackTrace();
}
}
private void unpairDevice(BluetoothDevice device) {
try {
Method method = device.getClass().getMethod("removeBond", (Class[]) null);
method.invoke(device, (Object[]) null);
} catch (Exception e) {
e.printStackTrace();
}
}
private void getPairedDevices() {
Set<BluetoothDevice> pairedDevice = btAdapter.getBondedDevices();
if(pairedDevice.size()>0)
{
for(BluetoothDevice device : pairedDevice)
{
arrayListpaired.add(device.getName()+"\n"+device.getAddress());
arrayListPairedBluetoothDevices.add(device);
}
}
adapter.notifyDataSetChanged();
}
public class ListItemClicked implements OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
bdDevice = arrayListBluetoothDevices.get(position);
Log.i("Log", "The device : " + bdDevice.toString());
getPairedDevices();
createBond(bdDevice);
adapter.notifyDataSetChanged();
Log.i("Log", "The bond is created: with" + bdDevice.toString());
}
}
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
BluetoothSocket tmp = null;
mmDevice = device;
try {
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) { }
mmSocket = tmp;
}
public void run() {
btAdapter.cancelDiscovery();
try {
mmSocket.connect();
} catch (IOException connectException) {
try {
mmSocket.close();
} catch (IOException closeException) { }
return;
}
mHandler.obtainMessage(SUCCESS_CONNECT, mmSocket).sendToTarget();
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer; // 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
buffer = new byte[1024];
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI activity
mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
} catch (IOException e) {
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) { }
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
#Override
protected void onDestroy() {
super.onDestroy();
btAdapter.cancelDiscovery();
unregisterReceiver(receiver);
}
class ListItemClickedonPaired implements OnItemClickListener
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
bdDevice = arrayListPairedBluetoothDevices.get(position);
unpairDevice(bdDevice);
//arrayListPairedBluetoothDevices.clear();
}
}
private void makeDiscoverable() {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 150);
startActivity(discoverableIntent);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_CANCELED) {
Toast.makeText(MainActivity.this, "Bluetooth must be enabled to start scanning", Toast.LENGTH_SHORT).show();
} else
{
Toast.makeText(MainActivity.this, "Click on TURN_OFF to disable bluetooth", Toast.LENGTH_LONG).show();
}
}
private void setupMessageButton1() {
//1.get a reference for my button
Button messageButton = (Button) findViewById(R.id.button1);
//2. Set the click to run my code
messageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listAdapter.clear();
arrayListBluetoothDevices.clear();
btAdapter.startDiscovery();
}
});
}
private void setupMessageButton2() {
//1.get a reference to the button.
Button messageButton = (Button) findViewById(R.id.button2);
//2. set the click listener to run my code.
messageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (btAdapter.isEnabled()) {
listAdapter.clear();
btAdapter.disable();
} else
{
Toast.makeText(MainActivity.this, "Dont worry it's already off", Toast.LENGTH_SHORT).show();
}
}
});
}
private void setupMessageButton3() {
//1.get a reference for my button
Button messageButton = (Button) findViewById(R.id.button3);
//2. Set the click to run my code
messageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
private void setupMessageButton4() {
//1.get a reference for my button
Button messageButton = (Button) findViewById(R.id.button4);
//2. Set the click to run my code
messageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btAdapter.enable();
}
});
}
private void setupMessageButton5() {
//1.get a reference for my button
Button messageButton = (Button) findViewById(R.id.button5);
//2. Set the click to run my code
messageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
makeDiscoverable();
}
});
}
}
Concerning the log i have that message :
"D/BluetoothUtils﹕ isSocketAllowedBySecurityPolicy start : device null"
"W/BluetoothAdapter﹕ getBluetoothService() called with no BluetoothManagerCallback"
"D/BluetoothSocket﹕ connect(), SocketState: INIT, mPfd: {ParcelFileDescriptor: FileDescriptor[75]} "
public class ListItemClicked implements OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
bdDevice = arrayListBluetoothDevices.get(position);
Log.i("Log", "The device : " + bdDevice.toString());
createBond(bdDevice);
adapter.notifyDataSetChanged();
ConnectThread connect = new ConnectThread(bdDevice);
connect.start();
}
}
For the connection, i use the ConnectThread found in Bluetooth APi developer Website:
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
BluetoothSocket tmp = null;
mmDevice = device;
try {
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) { }
mmSocket = tmp;
}
public void run() {
btAdapter.cancelDiscovery();
try {
mmSocket.connect();
} catch (IOException connectException) {
try {
mmSocket.close();
} catch (IOException closeException) { }
return;
}
mHandler.obtainMessage(SUCCESS_CONNECT, mmSocket).sendToTarget();
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
it's ok i found the solution, i had the problem with the phone i'm using, he is not supporting SPP.
Thank you anyway
i am using this code for printing:
public class BPrinterActivity extends Activity implements Runnable {
protected static final String TAG = "TAG";
private static final int REQUEST_CONNECT_DEVICE = 1;
private static final int REQUEST_ENABLE_BT = 2;
private Button mScan, mPrint, mDisc;
private UUID applicationUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private ProgressDialog mBluetoothConnectProgressDialog;
private BluetoothSocket mBluetoothSocket;
private BluetoothDevice mBluetoothDevice;
private BluetoothAdapter mBluetoothAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_bprinter);
mScan = (Button) findViewById(R.id.Scan);
mScan.setOnClickListener(new View.OnClickListener() {
public void onClick(View mView) {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
Toast.makeText(BPrinterActivity.this, "Message1", 2000).show();
} else {
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent,REQUEST_ENABLE_BT);
} else {
ListPairedDevices();
Intent connectIntent = new Intent(BPrinterActivity.this,DeviceListActivity.class);
startActivityForResult(connectIntent,REQUEST_CONNECT_DEVICE);
}
}
}
});
mPrint = (Button) findViewById(R.id.mPrint);
mPrint.setOnClickListener(new View.OnClickListener() {
public void onClick(View mView) {
Thread t = new Thread() {
public void run() {
try {
String BILL = "";
BILL = "1234567812345678ABCDEFGH";
BILL="الرئيسية";
BILL = "ABCDEFGH";
OutputStream os = mBluetoothSocket.getOutputStream();
os.write(BILL.getBytes());
} catch (Exception e) {
Log.e("Main", "Exe ", e);
}
}
};
t.start();
}
});
mDisc = (Button) findViewById(R.id.dis);
mDisc.setOnClickListener(new View.OnClickListener() {
public void onClick(View mView) {
if (mBluetoothAdapter != null)
mBluetoothAdapter.disable();
}
});
}// onCreate
#Override
protected void onDestroy() {
super.onDestroy();
try {
if (mBluetoothSocket != null)
mBluetoothSocket.close();
} catch (Exception e) {
Log.e("Tag", "Exe ", e);
}
}
#Override
public void onBackPressed() {
try {
if (mBluetoothSocket != null)
mBluetoothSocket.close();
} catch (Exception e) {
Log.e("Tag", "Exe ", e);
}
setResult(RESULT_CANCELED);
finish();
}
public void onActivityResult(int mRequestCode, int mResultCode,Intent mDataIntent) {
super.onActivityResult(mRequestCode, mResultCode, mDataIntent);
switch (mRequestCode) {
case REQUEST_CONNECT_DEVICE:
if (mResultCode == Activity.RESULT_OK) {
Bundle mExtra = mDataIntent.getExtras();
String mDeviceAddress = mExtra.getString("DeviceAddress");
Log.v(TAG, "Coming incoming address " + mDeviceAddress);
mBluetoothDevice = mBluetoothAdapter.getRemoteDevice(mDeviceAddress);
mBluetoothConnectProgressDialog = ProgressDialog.show(this,"Connecting...", mBluetoothDevice.getName() + " : "+ mBluetoothDevice.getAddress(), true, false);
Thread mBlutoothConnectThread = new Thread(this);
mBlutoothConnectThread.start();
// pairToDevice(mBluetoothDevice); This method is replaced by
// progress dialog with thread
}
break;
case REQUEST_ENABLE_BT:
if (mResultCode == Activity.RESULT_OK) {
ListPairedDevices();
Intent connectIntent = new Intent(BPrinterActivity.this,DeviceListActivity.class);
startActivityForResult(connectIntent, REQUEST_CONNECT_DEVICE);
} else {
Toast.makeText(BPrinterActivity.this, "Message", 2000).show();
}
break;
}
}
private void ListPairedDevices() {
Set<BluetoothDevice> mPairedDevices = mBluetoothAdapter.getBondedDevices();
if (mPairedDevices.size() > 0) {
for (BluetoothDevice mDevice : mPairedDevices) {
Log.v(TAG, "PairedDevices: " + mDevice.getName() + " "+ mDevice.getAddress());
}
}
}
public void run() {
try {
mBluetoothSocket = mBluetoothDevice.createRfcommSocketToServiceRecord(applicationUUID);
mBluetoothAdapter.cancelDiscovery();
mBluetoothSocket.connect();
mHandler.sendEmptyMessage(0);
} catch (IOException eConnectException) {
Log.d(TAG, "CouldNotConnectToSocket", eConnectException);
closeSocket(mBluetoothSocket);
return;
}
}
private void closeSocket(BluetoothSocket nOpenSocket) {
try {
nOpenSocket.close();
Log.d(TAG, "SocketClosed");
} catch (IOException ex) {
Log.d(TAG, "CouldNotCloseSocket");
}
}
private Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
mBluetoothConnectProgressDialog.dismiss();
Toast.makeText(BPrinterActivity.this, "DeviceConnected", 5000).show();
}
};
public static byte intToByteArray(int value) {
byte[] b = ByteBuffer.allocate(4).putInt(value).array();
for (int k = 0; k < b.length; k++) {
System.out.println("Selva [" + k + "] = " + "0x"+ UnicodeFormatter.byteToHex(b[k]));
}
return b[3];
}
public byte[] sel(int val) {
ByteBuffer buffer = ByteBuffer.allocate(2);
buffer.putInt(val);
buffer.flip();
return buffer.array();
}
}
this code work very well but before printing this will going to scan device pairing it and then print now i have printer device address now i directly want to print without scan or paring