i am trying to use my android phone to connect to the pc or hc01 but know the code that i write cannot connect to the phone now so anyone can help me out
and the UUID what should i use or have anyone have some demon for me to try out
thanks
i don't why i click and it always connect fail and the logcat will get
com.example.lord1.myapplication123123 W/BluetoothAdapter: getBluetoothService() called with no BluetoothManagerCallback
this is my code:
private void discover(View view){
// Check if the device is already discovering
if(mBTAdapter.isDiscovering()){
mBTAdapter.cancelDiscovery();
Toast.makeText(getApplicationContext(),"Discovery stopped",Toast.LENGTH_SHORT).show();
}
else{
if(mBTAdapter.isEnabled()) {
mBTArrayAdapter.clear(); // clear items
mBTAdapter.startDiscovery();
Toast.makeText(getApplicationContext(), "Discovery started", Toast.LENGTH_SHORT).show();
registerReceiver(blReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
}
else{
Toast.makeText(getApplicationContext(), "Bluetooth not on", Toast.LENGTH_SHORT).show();
}
}
}
final BroadcastReceiver blReceiver = 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);
// add the name to the list
mBTArrayAdapter.add(device.getName() + "\n" + device.getAddress());
mBTArrayAdapter.notifyDataSetChanged();
}
}
};
private void listPairedDevices(View view){
mPairedDevices = mBTAdapter.getBondedDevices();
if(mBTAdapter.isEnabled()) {
// put it's one to the adapter
for (BluetoothDevice device : mPairedDevices)
mBTArrayAdapter.add(device.getName() + "\n" + device.getAddress());
Toast.makeText(getApplicationContext(), "Show Paired Devices", Toast.LENGTH_SHORT).show();
}
else
Toast.makeText(getApplicationContext(), "Bluetooth not on", Toast.LENGTH_SHORT).show();
}
private AdapterView.OnItemClickListener mDeviceClickListener = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
if(!mBTAdapter.isEnabled()) {
Toast.makeText(getBaseContext(), "Bluetooth not on", Toast.LENGTH_SHORT).show();
return;
}
mBluetoothStatus.setText("Connecting...");
// Get the device MAC address, which is the last 17 chars in the View
String info = ((TextView) v).getText().toString();
final String address = info.substring(info.length() - 17);
final String name = info.substring(0,info.length() - 17);
// Spawn a new thread to avoid blocking the GUI one
new Thread()
{
public void run() {
boolean fail = false;
BluetoothDevice device = mBTAdapter.getRemoteDevice(address);
try {
mBTSocket = createBluetoothSocket(device);
} catch (IOException e) {
fail = true;
Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_SHORT).show();
}
// Establish the Bluetooth socket connection.
try {
mBTSocket.connect();
} catch (IOException e) {
try {
fail = true;
mBTSocket.close();
mHandler.obtainMessage(CONNECTING_STATUS, -1, -1)
.sendToTarget();
} catch (IOException e2) {
//insert code to deal with this
Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_SHORT).show();
}
}
if(fail == false) {
mConnectedThread = new ConnectedThread(mBTSocket);
mConnectedThread.start();
mHandler.obtainMessage(CONNECTING_STATUS, 1, -1, name)
.sendToTarget();
}
}
}.start();
}
};
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
I made an app which connects to bluetooth and sends and receive data in an activity. Now I have updates in the app and has to create another activities which connects to the same bluetooth device and transfer data. So I am planning to connect to bluetooth device in my second activity which has some buttons which calls for another activities. I need to retain the bluetooth connection I made in the second activity throughout the activities that are called from the second activity using buttons till the user press back button from second activity (exiting second activity). Please explain how I should change my code to make this happen. This is my current code which is used for single activity bluetooth connection.
public class ViewBoardStatus extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_board_status);
mOutStringBuffer = new StringBuffer("");
IntentFilter filter = new IntentFilter();
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
List<String> paireddevicesarray = new ArrayList<>();
int iNoOfPariedDev = pairedDevices.size();
int iDeviceCntr = 0;
DevAddressString = new String[iNoOfPariedDev][2];
for (BluetoothDevice device : pairedDevices)
{
DevAddressString[iDeviceCntr][0] = device.getAddress();
DevAddressString[iDeviceCntr][1] = device.getName();
iDeviceCntr++;
if (iDeviceCntr > iNoOfPariedDev)
break;
}
ArrayList<String> aList = new ArrayList<String>();
aList.add("Select Device");
for (int i = 0; i < iDeviceCntr; i++)
{
aList.add(DevAddressString[i][1]);
}
final ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, aList);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp_paireddevices.setAdapter(dataAdapter);
sp_paireddevices.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parentView,
View selectedItemView, int position, long id) {
// Object item = parentView.getItemAtPosition(position);
Log.e(TAG, "Executing On ITEM SELECTED");
int iLoc = sp_paireddevices.getSelectedItemPosition();
if (iLoc != 0)
{
Toast.makeText(getApplicationContext(), " Connecting to hardware please wait..", Toast.LENGTH_SHORT).show();
iBTDevSelcted = 1;
Log.e(TAG, "Toast message of Connecting");
address = DevAddressString[iLoc - 1][0];
Log.e(TAG, "Calling OnResume Function");
onResume();
}
else
{
Toast.makeText(getApplicationContext(), " Please select Bluetooth Device", Toast.LENGTH_SHORT).show();
}
}
public void onNothingSelected(AdapterView<?> arg0) {// do nothing
}
});
lvParaHeader.setOnTouchListener(new View.OnTouchListener()
{
#Override
public boolean onTouch(View v, MotionEvent event)
{
if(touchSource == null)
touchSource = v;
if(v == touchSource)
{
lvParaValue.dispatchTouchEvent(event);
if(event.getAction() == MotionEvent.ACTION_UP)
{
clickSource = v;
touchSource = null;
}
}
return false;
}
});
lvParaValue.setOnTouchListener(new View.OnTouchListener()
{
#Override
public boolean onTouch(View v, MotionEvent event)
{
if(touchSource == null)
touchSource = v;
if(v == touchSource)
{
lvParaHeader.dispatchTouchEvent(event);
if(event.getAction() == MotionEvent.ACTION_UP)
{
clickSource = v;
touchSource = null;
}
}
return false;
}
});
lvParaHeader.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(parent == clickSource) {
// Do something with the ListView was clicked
}
}
});
lvParaValue.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(parent == clickSource) {
// Do something with the ListView was clicked
}
}
});
lvParaHeader.setOnScrollListener(new OnScrollListener() {
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if(view == clickSource)
lvParaValue.setSelectionFromTop(firstVisibleItem, view.getChildAt(0).getTop() + offset);
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {}
});
lvParaValue.setOnScrollListener(new OnScrollListener() {
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if(view == clickSource)
lvParaHeader.setSelectionFromTop(firstVisibleItem, view.getChildAt(0).getTop() + offset);
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {}
});
sp_datatype.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
Log.e(l,"Starting ON Item Selected");
if (sp_paireddevices.getSelectedItemPosition()>0)
{
if (sp_datatype.getSelectedItemPosition() == 1) {
sGetRequest = sGetElectricalPara;
sendMessage(sGetRequest);
}
if (sp_datatype.getSelectedItemPosition() == 2) {
sGetRequest = sGetGprsPara;
sendMessage(sGetRequest);
}
if (sp_datatype.getSelectedItemPosition() == 3) {
sGetRequest = sGetSystemPara;
sendMessage(sGetRequest);
}
if (sp_datatype.getSelectedItemPosition() == 4) {
sGetRequest = sGetRS485Para;
sendMessage(sGetRequest);
}
}
else
Toast.makeText(getApplicationContext(), " Connect to a Device and Refresh ", Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent)
{
}
});
bt_Refresh.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Log.e(l,"Refresh Button OnClick");
if (sp_paireddevices.getSelectedItemPosition()>0)
{
if (sp_datatype.getSelectedItemPosition() == 0) {
Toast.makeText(getApplicationContext(), " Select a Parameter to Refresh ", Toast.LENGTH_SHORT).show();
}
if (sp_datatype.getSelectedItemPosition() == 1) {
sGetRequest = sGetElectricalPara;
sendMessage(sGetRequest);
Log.e(l, "Send Message Called");
}
if (sp_datatype.getSelectedItemPosition() == 2) {
sGetRequest = sGetGprsPara;
sendMessage(sGetRequest);
}
if (sp_datatype.getSelectedItemPosition() == 3) {
sGetRequest = sGetSystemPara;
sendMessage(sGetRequest);
}
if (sp_datatype.getSelectedItemPosition() == 4) {
sGetRequest = sGetRS485Para;
sendMessage(sGetRequest);
}
Log.e(l, "Send Message Called");
}
else
Toast.makeText(getApplicationContext(), " Connect to a Device and Refresh ", Toast.LENGTH_SHORT).show();
}
});
h = new Handler()
{
public void handleMessage(android.os.Message msg)
{
Log.e(l, "Starting Handler");
int strlen;
switch (msg.what)
{
case RECIEVE_MESSAGE:
Log.d(l, "data received = " );
byte[] readBuf = (byte[]) msg.obj;
String strIncom = new String(readBuf, 0, msg.arg1);
String strMsg = new String();
sb.append(strIncom);
int endOfLineIndex = sb.indexOf("#");
if (endOfLineIndex > 0)
{ // if end-of-line,
sJsonData = sb.substring(1, endOfLineIndex); // extract string
sb.delete(0, sb.length());
// and clear
try
{
Log.e(l, "Starting Try of Handler");
Log.e(l, "Data Received: "+sJsonData);
strlen = sJsonData.length();
Log.e(l, "String Length Obtained");
JSONObject mainobject = new JSONObject(sJsonData);
Log.e(l, "main object created");
sDataType = mainobject.getString("DATA_TYPE");
Log.e(l, "Data Type Obtained");
//tv_jsonlength.setText(String.valueOf(strlen));
//tv_JsonPara.setText(TempHeader);
iSelectedParaPostion=sp_datatype.getSelectedItemPosition();
if(sDataType.trim().equalsIgnoreCase("PARA"))
{
if(iSelectedParaPostion==1)
{
sCurrentJsonData = sJsonData;
Log.e(l, "sCurrentJsonData set to sJsonData");
//tv_jsonstring.setText(sCurrentJsonData);
jsonparseelectricalpara();
}
}
if(sDataType.trim().equalsIgnoreCase("GPRS"))
{
if(iSelectedParaPostion==2)
{
sCurrentJsonData = sJsonData;
Log.e(l, "sCurrentJsonData set to sJsonData");
//tv_jsonstring.setText(sCurrentJsonData);
jsonparsegprsdata();
}
}
if(sDataType.trim().equalsIgnoreCase("SYSTEM"))
{
if(iSelectedParaPostion==3)
{
sCurrentJsonData = sJsonData;
Log.e(l, "sCurrentJsonData set to sJsonData");
//
// tv_jsonstring.setText(sCurrentJsonData);
jsonparseSystem();
}
}
}
catch (Exception e)
{
Log.e(l, "CATCH OF HANDLER");
}
}
break;
}
}
};
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); // get Bluetooth adapter
checkBTState();
}//oncreate
private void checkBTState()
{
// Check for Bluetooth support and then check to make sure it is turned on
// Emulator doesn't support Bluetooth and will return null
if(mBluetoothAdapter==null) {
// Log.d(TAG, "error, bluetooth not supported");
} else {
if (mBluetoothAdapter.isEnabled()) {
// Log.d(TAG, "...Bluetooth ON...");
} else {
//Prompt user to turn on Bluetooth
tvconnectionstatus.setText("");
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
}
private void errorExit(String title, String message)
{
Toast.makeText(getBaseContext(), title + " - " + message, Toast.LENGTH_LONG).show();
finish();
}
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});
Log.e(TAG, "Bluetooth Socket Creation TRY EXECUTED");
return (BluetoothSocket) m.invoke(device, MY_UUID);
}
catch (Exception e2)
{
errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
Log.e(TAG, "Bluetooth Socket Creation CATCH EXECUTED");
}
}
Log.e(TAG, "Exiting Socket Creation Method");
return device.createRfcommSocketToServiceRecord(MY_UUID);
}
public void onResume()
{
super.onResume();
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
Log.e(TAG, "Starting OnResume Method");
if (iBTDevSelcted == 0) {
Toast.makeText(getApplicationContext(), " Please select Bluetooth Device", Toast.LENGTH_SHORT).show();
return;
}
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
Log.e(TAG, "Obtaining REMOTE DEVICE address");
try {
btSocket = createBluetoothSocket(device);
Log.e(TAG, "BT SOCKET Created");
} catch (IOException e) {
errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
}
mBluetoothAdapter.cancelDiscovery();
Log.e(TAG, "BT Discovery CANCELLED");
try
{
Log.e(TAG, "TRY STATEMENT OF BT CONNECTION CREATION");
btSocket.connect();
String connectedto = "Connected to: " + sp_paireddevices.getSelectedItem().toString();
tvconnectionstatus.setText(connectedto);
}
catch (IOException e)
{
Log.e(TAG, "CATCH STATEMENT OF BLUETOOTH CONNECTION CREATION");
try {
btSocket.close();
Log.e(TAG, "Bluetooth Socket Closed");
tvconnectionstatus.setText("");
} catch (IOException e2) {
errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
Log.e(TAG, "Unable to Close bluetooth connection");
}
}
// Create a data stream so we can talk to server.
// Log.d(TAG, "...Create Socket...");
mConnectedThread = new ConnectedThread(btSocket);
Log.e(TAG, "Connection Thread Created");
mConnectedThread.start();
Log.e(TAG, "Connection Thread Started");
}
#Override
public void onPause()
{
super.onPause();
// Log.d(TAG, "...In onPause()...");
if(iBTDevSelcted==1) {
try {
btSocket.close();
tvconnectionstatus.setText("");
} catch (IOException e2) {
errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
}
}
}
private class ConnectedThread extends Thread
{
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket)
{
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try
{
Log.e(TAG, "Trying to get Temp Input/Output Stream");
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
Log.e(TAG, "Input/Output Stream Obtained");
}
catch (IOException e)
{
Log.e(TAG, "I/O Stream CATCH STATEMENT");
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run()
{
Log.e(TAG, "Starting RUN Method");
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 {
Log.e(TAG, "TRY of RUN Method Started");
// Read from the InputStream
bytes = mmInStream.read(buffer); // Get number of bytes and message in "buffer"
h.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget(); // Send to message queue Handler
Log.e(l,"Run Executed");
Log.e(TAG, "TRY of RUN Method Completed");
} catch (IOException e)
{
Log.e(TAG, "CATCH of RUN Method");
break;
}
}
}
public void write(String s) throws IOException
{
mmOutStream.write(s.getBytes());
tvconnectionstatus.setText(s);
sGetRequest=sReset;
}
}//connectthread
private void sendMessage(String message)
{
ConnectedThread ct;
Log.e(l,"Connected Thread Object Created");
ct = mConnectedThread;
try {
ct.write(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}//class
I have following problem - I need to send data to my usb device and read tag of the device. First I need to turn on device - that's what table pal does. Next, when response from device equals DAAD0674016F6B26 I need to start scan - table readId. After that depends if response is DAAD046F62ADA900 - that means that in 3 sec device didn't found tag to scan and device turned off. My task is to send again command to turn it on ... and again, and again and so on (I know it's quite expensive - command every 3 sec - it wasn't my idea). But , when the response is different than DAAD046F62ADA900 - that's my tag :)To sum up - if response is DAAD046F62ADA900 I need to send command to scan again I try to do it with while loop :
while(shouldReceive) {
sendCommand
}
but the screen freezes so I tried to do it in thread , and right now it looks like this :
final Thread receive= new Thread(new Runnable() {
public UsbDevice device;
#Override
public void run() {
usbManager = (UsbManager) getActivity().getSystemService(Context.USB_SERVICE);
PendingIntent mPermissionIntent = PendingIntent.getBroadcast(getContext(), 0, new Intent(ACTION_USB_PERMISSION), 0);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
getActivity().registerReceiver(usbReceiver, filter);
shouldReceaive = true;
HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();
Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
while (deviceIterator.hasNext()) {
final UsbDevice device = deviceIterator.next();
if (device.getVendorId() == 1659 && device.getProductId() == 8963) {
this.device = device;
usbManager.requestPermission(device, mPermissionIntent);
break;
}
}
final UsbConnector.CallbackListener listener = new UsbConnector.CallbackListener() {
#Override
public void onStatusChanged(UsbConnector.Status newStatus) {
Toast.makeText(getContext(), "Status" + newStatus, Toast.LENGTH_SHORT).show();
}
#Override
public void onScanCompleted(String result) {
Toast.makeText(getContext(), "Result" + result, Toast.LENGTH_SHORT).show();
}
};
shouldReceaive = true;
UsbConnector connector = new UsbConnector(getContext(), device, listener);
connector.run();
connector.send(pal);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] received = connector.receive(36);
if (received == null) {
Toast.makeText(getContext(), "Błąd inicjalizacji skanera", Toast.LENGTH_SHORT).show();
}
if (received != null) {
String response = null;
long longValue = ByteBuffer.wrap(received).getLong();
response = Long.toHexString(longValue).toUpperCase();
Toast.makeText(getContext(), "RESPONSE: " + response, Toast.LENGTH_SHORT).show();
if (response.contentEquals("DAAD0674016F6B26")) {
Toast.makeText(getContext(), "Rozpoczynam skanowanie ...", Toast.LENGTH_SHORT).show();
connector.send(readId);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] receivedTag = connector.receive(36);
if (receivedTag != null) {
String tag = null;
long tagValue = ByteBuffer.wrap(receivedTag).getLong();
tag = Long.toHexString(tagValue).toUpperCase();
while (tag.contentEquals("DAAD046F62ADA900")) {
Toast.makeText(getContext(), "PING, SKANUJE DALEJ!", Toast.LENGTH_SHORT).show();
connector.send(readId);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String tag2 = null;
long tagValue2 = ByteBuffer.wrap(receivedTag).getLong();
tag2 = Long.toHexString(tagValue2).toUpperCase();
Toast.makeText(getContext(), "ZESKANOWANY TAG!: " + tag2, Toast.LENGTH_SHORT).show();
for (Car cary : carList) {
if (tag2.contentEquals(cary.getmNumber())) {
Log.e(TAG, "setCars: JEST");
} else {
Log.e(TAG, "setCars: NIE MA");
}
}
}
} else {
Toast.makeText(getContext(), "Błąd przy inicjalziacji skanera", Toast.LENGTH_SHORT).show();
}
}
}
});
mScan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
receive.run();
}
});
but problem still exists. Screen freezes and user can do nothing. Any idea how to solve this problem ?
When you invoke run() method, it's executed on the calling thread (in your case on UI thread).
#Override
public void onClick(View v) {
receive.run();
}
Try this:
#Override
public void onClick(View v) {
receive.start();
}
I have an Arduino Bluetooth shield HC-05. I paired the Bluetooth shield first with Android device and tried to send data to Arduino via Bluetooth shield. Android app sends data to the shield. But Arduino not receiving the command more than (4 to 13) times I think my app not holding the connection properly with the Bluetooth shield, I am not sure about the problem. I tried with the same Arduino code with some other Android application. It was working well. So problem is in my code only. I am using log to monitor the flow of code. The data is sending from the Android device and the Bluetooth is live and still paired. I think Bluetooth shield was not receiving or it was receiving and not passing the data to Arduino. I am troubling for couple of weeks.
Thanks in Advance !!
My code goes here...
private BluetoothAdapter mBluetoothAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
private static String address = "98:D3:31:30:25:DC";//old: 20:14:12:03:12:42, 98:D3:31:30:25:DC
private static final UUID MY_UUID = UUID
.fromString("00001101-0000-1000-8000-00805F9B34FB");
private InputStream inStream = null;
Handler handler = new Handler();
byte delimiter = 10;
boolean stopWorker = false;
int readBufferPosition = 0;
byte[] readBuffer = new byte[1024];
//
//Bluetooth sender ends
//
//
private final BroadcastReceiver commandAction = new BroadcastReceiver() {
#Override
public void onReceive(Context context2, Intent intent2) {
String com = intent2.getStringExtra("key");
commandAction(com);
Toast.makeText(context2, "commandAction:"+com, Toast.LENGTH_SHORT).show();
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
commandAction("up");
}
});
GCMRegistrar.checkDevice( this );
GCMRegistrar.checkManifest( this );
final String regId = GCMRegistrar.getRegistrationId( this );
if( regId.equals( "" ) ) {
GCMRegistrar.register( this, "501396392354" );
Toast.makeText(this," 501396392354", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(this,regId, Toast.LENGTH_SHORT).show();
Log.v( TAG2, "Already registered" );
Log.v(TAG2, "Registration id is: " + regId );
}
startService(new Intent(MainActivity.this, LocationService.class));
CheckBt();
Connect();
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
Log.e("Jon", device.toString());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public Object onRetainNonConfigurationInstance() {
if (mAccessory != null) {
return mAccessory;
} else {
return super.onRetainNonConfigurationInstance();
}
}
#Override
public void onResume() {
super.onResume();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("in.robot.gcm.commandaction");
registerReceiver(commandAction, intentFilter);
if (mInputStream != null && mOutputStream != null) {
return;
}
}
#Override
public void onPause() {
super.onPause();
unregisterReceiver(commandAction);
closeAccessory();
}
#Override
public void onDestroy() {
unregisterReceiver(mUsbReceiver);
stopService(new Intent(MainActivity.this, LocationService.class));
try {
btSocket.close();
} catch (IOException e) {
}
super.onDestroy();
}
private void openAccessory(UsbAccessory accessory) {
mFileDescriptor = mUsbManager.openAccessory(accessory);
if (mFileDescriptor != null) {
mAccessory = accessory;
FileDescriptor fd = mFileDescriptor.getFileDescriptor();
mInputStream = new FileInputStream(fd);
mOutputStream = new FileOutputStream(fd);
Log.d(TAG, "accessory opened");
} else {
Log.d(TAG, "accessory open fail");
}
}
private void closeAccessory() {
try {
if (mFileDescriptor != null) {
mFileDescriptor.close();
}
} catch (IOException e) {
} finally {
mFileDescriptor = null;
mAccessory = null;
}
}
public void commandAction(String command){
byte[] buffer = new byte[1];
MediaPlayer mp;
Toast.makeText(this,"in cmd action",Toast.LENGTH_SHORT).show();
if("up".equals(command)){
buffer[0]=(byte)0;
Log.v(TAG ,"up heay");
writeData("1");
Toast.makeText(this,"UP",Toast.LENGTH_SHORT).show();
}
else if("down".equals(command)) {
buffer[0]=(byte)1;
Log.v(TAG ,"down heay");
writeData("2");
}
else if("left".equals(command)){
buffer[0]=(byte)2;
writeData("3");
}
else if("right".equals(command)){
buffer[0]=(byte)3;
writeData("4");
}
else if("break".equals(command)){
buffer[0]=(byte)4;
writeData("0");
}
else if("camera left".equals(command)){
buffer[0]=(byte)5;
//writeData("0");
}
else if("camera right".equals(command)){
buffer[0]=(byte)6;
//writeData("0");
}
else if ("jigsaw1".equals(command)){
mp = MediaPlayer.create(MainActivity.this, R.raw.jigsaw1);
mp.start();
}
else if("jigsaw2".equals(command)){
mp = MediaPlayer.create(MainActivity.this, R.raw.jigsaw2);
mp.start();
}
else if("horn".equals(command)){
mp = MediaPlayer.create(MainActivity.this, R.raw.horn);
mp.start();
}
else if("start".equals(command)){
mp = MediaPlayer.create(MainActivity.this, R.raw.start);
mp.start();
}
else if("ghosts".equals(command)){
mp = MediaPlayer.create(MainActivity.this, R.raw.ghosts);
mp.start();
}
else if("flash on".equals(command)){
if((this.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)) && !(isLighOn)){
cam = Camera.open();
Parameters params = cam.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_ON);
cam.setParameters(params);
cam.startPreview();
isLighOn=true;
Log.v("camera","flash on");
}
else{Log.v("camera","flash not exsisted");}
}
else if("flash off".equals(command)){
if(isLighOn){
cam.stopPreview();
cam.release();
isLighOn=false;
Log.v("camera","flash off");
} }
else if("location on".equals(command)){
startService(new Intent(MainActivity.this, LocationService.class));
}
else if("location off".equals(command)){
stopService(new Intent(MainActivity.this, LocationService.class));
}
else if("speed min".equals(command)){
buffer[0]=(byte)7;
}
else if("speed min".equals(command)){
buffer[0]=(byte)8;
}
else if("speed max".equals(command)){
buffer[0]=(byte)9;
}
else{
Log.v(TAG ,"no command recieved");}
if (mOutputStream != null) {
try {
mOutputStream.write(buffer);
} catch (IOException e) {
Log.e(TAG, "write failed", e);
}
}
}
//
//
//
//
private void CheckBt() {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (!mBluetoothAdapter.isEnabled()) {
Toast.makeText(getApplicationContext(), "Bluetooth Disabled !",
Toast.LENGTH_SHORT).show();
}
if (mBluetoothAdapter == null) {
Toast.makeText(getApplicationContext(),
"Bluetooth null !", Toast.LENGTH_SHORT)
.show();
}
}
public void Connect() {
Log.d(TAG, address);
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
Log.d(TAG, "Connecting to ... " + device);
Toast.makeText(this, "Connecting to...", Toast.LENGTH_SHORT).show();
mBluetoothAdapter.cancelDiscovery();
try {
btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
btSocket.connect();
Log.d(TAG, "Connection made.");
Toast.makeText(this, "Connection made Successful..", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
Log.d(TAG, "Unable to end the connection");
Toast.makeText(this, "Unable to end the connection", Toast.LENGTH_SHORT).show();
}
Log.d(TAG, "Socket creation failed");
Toast.makeText(this, "connection creation failed", Toast.LENGTH_SHORT).show();
}
//beginListenForData();
}
private void writeData(String data) {
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {
Log.d(TAG, "Bug BEFORE Sending stuff", e);
}
String message = data;
byte[] msgBuffer = message.getBytes();
try {
outStream.write(msgBuffer);
Toast.makeText(this, "Data Send Successful..", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Log.d(TAG, "Bug while sending stuff", e);
Toast.makeText(this, "Data Send Error..", Toast.LENGTH_SHORT).show();
}
}
}
outStream.write(msgBuffer);
It writes only first bit. how to write 8 bit out of it.If we are sending 00000001 means it writes only 0. But we want to write whole 8 bit how to achieve it.
public class MainActivity extends ActionBarActivity {
private ToggleButton power, simulation, reset, pause, replay, diagnose,
abs, emergency;
private static final String TAG = "bluetooth1";
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 = "00:12:02:28:75:34";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
power = (ToggleButton) findViewById(R.id.toggleButton1);
simulation = (ToggleButton) findViewById(R.id.simulation_tb);
reset = (ToggleButton) findViewById(R.id.reset_bt);
pause = (ToggleButton) findViewById(R.id.pause_bt);
replay = (ToggleButton) findViewById(R.id.replay_bt);
diagnose = (ToggleButton) findViewById(R.id.diagnose_bt);
abs = (ToggleButton) findViewById(R.id.abs_bt);
emergency = (ToggleButton) findViewById(R.id.emergency_bt);
btAdapter = BluetoothAdapter.getDefaultAdapter();
checkBTState();
power.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (power.isChecked()) {
String str = "1";
int i = Integer.parseInt(str);
String binarystr = Integer.toBinaryString(i);
char[] buffer = new char[binarystr.length()];
binarystr.getChars(0, binarystr.length(), buffer, 0);
System.out.println("char array:: "
+ Arrays.toString(buffer));
byte[] binaryFormat = getbyteFromString(buffer);
for (byte b : binaryFormat) {
sendData(Integer.toBinaryString(b & 255 | 256)
.substring(1));
}
Toast.makeText(getApplicationContext(), "LED ON",
Toast.LENGTH_LONG).show();
} else {
sendData("0");
Toast.makeText(getApplicationContext(), "LED OFF",
Toast.LENGTH_LONG).show();
}
}
});
}
#Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(getString(R.string.const_closeApp))
.setPositiveButton(getString(R.string.const_yes),
dialogClickListener)
.setNegativeButton(getString(R.string.const_no),
dialogClickListener).show();
}
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
// LocalBroadcastManager.getInstance(getApplicationContext()).unregisterReceiver(new
// BTStateChangedBroadcastReceiver());
System.exit(0);
finish();
break;
case DialogInterface.BUTTON_NEGATIVE:
// No button clicked
break;
}
}
};
private void checkBTState() {
// Check for Bluetooth support and then check to make sure it is turned
// on
// Emulator doesn't support Bluetooth and will return null
if (btAdapter == null) {
errorExit("Fatal Error", "Bluetooth not support");
} else {
if (btAdapter.isEnabled()) {
Log.d(TAG, "...Bluetooth ON...");
} else {
// Prompt user to turn on Bluetooth
Intent enableBtIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
}
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) {
Log.e(TAG, "Could not create Insecure RFComm Connection", e);
}
}
return device.createRfcommSocketToServiceRecord(MY_UUID);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private void sendData(String message) {
byte[] msgBuffer = message.getBytes();
Log.d(TAG, "...Send data: " + message + "...");
try {
outStream.write(msgBuffer);
Log.d(TAG, "...This is the value byte: " + msgBuffer);
} catch (IOException e) {
String msg = "In onResume() and an exception occurred during write: "
+ e.getMessage();
if (address.equals("00:00:00:00:00:00"))
msg = msg
+ ".\n\nUpdate your server address from 00:00:00:00:00:00 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);
}
}
private void errorExit(String title, String message) {
Toast.makeText(getBaseContext(), title + " - " + message,
Toast.LENGTH_LONG).show();
finish();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static byte[] getbyteFromString(char[] binarystr) {
int length = binarystr.length / 8;
if (binarystr.length % 8 > 0)
length++;
int iterationCount = length;
byte[] binaryFormat = new byte[iterationCount];
int iter = iterationCount - 1;
for (int i = binarystr.length - 1; i >= 0;) {
byte byt = 0x0;
for (int j = 0; j < 8; j++) {
if (i < 0)
break;
int b = binarystr[i] - 48;
byt = (byte) (byt + (b << j));
i--;
}
binaryFormat[iter] = byt;
iter--;
}
return binaryFormat;
}
#Override
public void onResume() {
super.onResume();
Log.d(TAG, "...onResume - try connect...");
// 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() + ".");
}
/*
* try { btSocket = device.createRfcommSocketToServiceRecord(MY_UUID); }
* catch (IOException e) { errorExit("Fatal Error",
* "In onResume() and socket create failed: " + e.getMessage() + "."); }
*/
// Discovery is resource intensive. Make sure it isn't going on
// when you attempt to connect and pass your message.
btAdapter.cancelDiscovery();
// Establish the connection. This will block until it connects.
Log.d(TAG, "...Connecting...");
try {
btSocket.connect();
Log.d(TAG, "...Connection ok...");
} 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.
Log.d(TAG, "...Create Socket...");
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();
Log.d(TAG, "...In onPause()...");
if (outStream != null) {
try {
outStream.flush();
} catch (IOException e) {
errorExit(
"Fatal Error",
"In onPause() and failed to flush output stream: "
+ e.getMessage() + ".");
} catch (NullPointerException e) {
e.printStackTrace();
}
}
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onPause() and failed to close socket."
+ e2.getMessage() + ".");
}
}
}
It looks like your code is not complete. Anyway, I suggest to use the DataInputStream / DataOutputStream of Android. Just wrap your streams into them. They provide methods for writing any kind of primitive datatype up to String with arbitrary encoding. All you need to do is use the writeString(...) method and use the read String method on the other side. This way you don't need to convert the String in order to write it into you stream and you don't need to care about how to reconstruct it from the stream.
If you only want to write Strings you can use the BufferedWriter which allows you to only write Strings to an stream, you can use it like this to stick it onto a 'OutputStream'
OutputStreamWriter osw = new OutputStreamWriter(outStream);
BufferedWriter writer = new BufferedWriter(osw);