我正在制作一个蓝牙应用程序,它连接到正在传输串行数据的蓝牙发送器/接收器。蓝牙设备最终将连接到传感器,这些传感器将提供需要在手机上显示的数据。截至目前,我正在使用模拟软件CoolTerm在我的应用程序和外部蓝牙设备之间来回发送数据。目前,我已成功使应用程序检测并连接到设备。但是我遇到了一些问题:
首先,任何人都知道如何安装CoolTerm(在技术上讲它可以在Mac和Windows上使用),但是当我尝试在Ubuntu上安装它时,它没有像在Windows上那样提供可执行文件。任何知道如何在ubuntu上安装它的人请告诉我我已经从那里下载了Linux版本tar球的步骤并将其解压缩。
虽然连接成功后我的应用程序发送了一个蓝牙设备收到的字符串,但我无法接收数据。我当前设置的方式我希望弹出一个Toast消息,告诉我当外部蓝牙设备发送给我时我收到了数据。 CoolTerm软件允许您发送数据,但由于某种原因,这不会显示在我的应用程序上。有任何想法吗?
最后,任何人都知道一个好的文本框小部件或我可以在我的应用程序中使用的东西,以将数据发送到外部蓝牙设备。现在我让应用程序在连接后立即发送一个字符串。
以下是YouTube链接:我已根据代码建议对此进行了一些细微更改。
点击[此处](http://www.youtube.com/watch?v=r55C77_ohi8“应用的youtube视频”)! 点击[此处](https://drive.google.com/?tab=mo&authuser=0#folders/0BwRY4KO_k7sUSGpLX0o4TDFCOFk“清洁代码格式”)!
这是代码
package com.example.intellicyclemobileside;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.ToggleButton;
public class MainActivity extends Activity {
ToggleButton toggle_discovery;
Button button;
ListView listView;
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
ArrayAdapter<String> mArrayAdapter;
ArrayAdapter<String> adapter;
ArrayList<String> pairedDevicesList;
ArrayList<String> unpairedDevicesList;
ArrayList<String> combinedDevicesList;
Set<BluetoothDevice> pairedDevices;
Set<String> unpairedDevices;
BroadcastReceiver mReceiver;
String selectedFromList;
String selectedFromListName;
String selectedFromListAddress;
BluetoothDevice selectedDevice;
/*
public BluetoothSocket mmSocket;
public BluetoothDevice mmDevice;*/
protected static final int SUCCESS_CONNECT = 0;
protected static final int MESSAGE_READ = 1;
final int STATE_CONNECTED = 2;
final int STATE_CONNECTING = 1;
final int STATE_DISCONNECTED = 0;
private final UUID MY_UUID = UUID.fromString("0001101-0000-1000-8000-00805F9B34FB");
private static final int REQUEST_ENABLE_BT = 1;
Handler mHandler = new Handler(){
public void handleMessage(Message msg){
super.handleMessage(msg);
switch(msg.what){
case SUCCESS_CONNECT:
// Do Something;
ConnectedThread connectedThread = new ConnectedThread((BluetoothSocket)msg.obj);
Toast.makeText(getApplicationContext(),"CONNECTED",0).show();
String s = "This string proves a socket connection has been established!!";
connectedThread.write(s.getBytes());
break;
case MESSAGE_READ:
byte[] readBuf = (byte[])msg.obj;
String string = new String(readBuf);
Toast.makeText(getApplicationContext(),string,0).show();
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.findDevices);
toggle_discovery = (ToggleButton) findViewById(R.id.deviceDiscoverable);
pairedDevicesList = new ArrayList<String>();
unpairedDevicesList = new ArrayList<String>();
unpairedDevices = new HashSet<String>();
listView = (ListView)findViewById(R.id.listView);
// Sets up Bluetooth
enableBT();
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
Toast.makeText(getApplicationContext(), "Searching for devices, please wait... ",Toast.LENGTH_SHORT).show();
// Checks for known paired devices
pairedDevices = mBluetoothAdapter.getBondedDevices();
displayCominedDevices();
//mBluetoothAdapter.cancelDiscovery();
}
});
toggle_discovery.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
makeDicoverable(1);
} else {
// The toggle is disabled
makeDicoverable(0);
}
}
});
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
// When clicked, show a toast with the TextView text
selectedFromList = (String) (listView.getItemAtPosition(position));
/*Debugging
Toast.makeText(getApplicationContext(), selectedFromList,Toast.LENGTH_SHORT).show();*/
String[] parts = selectedFromList.split(" ");
selectedFromListName = parts[0];
selectedFromListAddress = parts[1];
BluetoothDevice selectedDevice = selectedDevice(selectedFromListAddress);
mBluetoothAdapter.cancelDiscovery();
ConnectThread ct = new ConnectThread(selectedDevice);
ct.start();
//ConnectThread ConnectThread = new ConnectThread(selectedDevice);
//connectDevice();
/* Debug Help
Toast.makeText(getApplicationContext(), selectedFromListName,Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), selectedFromListAddress,Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(),selectedDevice.getAddress(), Toast.LENGTH_SHORT).show();*/
}
});
}
public void displayCominedDevices(){
displayPairedDevices();
displayDetectedDevices();
mArrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,removeDuplicates(unpairedDevicesList,pairedDevicesList));
listView.setAdapter(mArrayAdapter);
}
public BluetoothDevice selectedDevice(String deviceAddress){
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice device;
device = mBluetoothAdapter.getRemoteDevice(deviceAddress);
return device;
}
@SuppressLint("NewApi")
public String checkState(BluetoothSocket mmSocket2){
String state = "NOT_KNOWN";
if (mmSocket2.isConnected() == true){
state = "STATE_CONNECTED";
}
state = "STATE_DISCONNECTED";
Toast.makeText(getApplicationContext(), state, Toast.LENGTH_SHORT).show();
return state;
}
@SuppressWarnings("unchecked")
public ArrayList<String> removeDuplicates(ArrayList<String> s1, ArrayList<String> s2){
/*Debugging
Toast.makeText(getApplication(), "unpairedList " + s1.toString(),Toast.LENGTH_LONG).show();
Toast.makeText(getApplication(), "pairedList " + s2.toString(),Toast.LENGTH_LONG).show(); */
combinedDevicesList = new ArrayList<String>();
combinedDevicesList.addAll(s1);
combinedDevicesList.addAll(s2);
@SuppressWarnings("unchecked")
Set Unique_set = new HashSet(combinedDevicesList);
combinedDevicesList = new ArrayList<String>(Unique_set);
/*Debugging
Toast.makeText(getApplication(),"Combined List" + combinedDevicesList.toString(),Toast.LENGTH_LONG).show(); */
return combinedDevicesList;
}
public void enableBT(){
if (mBluetoothAdapter == null) {
// Device does not support Bluetooth
Toast.makeText(getApplicationContext(), "Bluetooth is not suppourted on Device",Toast.LENGTH_SHORT).show();
}
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
int resultCode = Activity.RESULT_OK;
if(resultCode < 1){
Toast.makeText(getApplicationContext(), "Please Accept Enabling Bluetooth Request!", Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(getApplicationContext(), "Enabling Bluetooth FAILED!", Toast.LENGTH_SHORT).show();
}
}
}
public void displayPairedDevices(){
// If there are paired devices
enableBT();
if (pairedDevices.size() > 0) {
//Toast.makeText(getApplicationContext(),"in loop",Toast.LENGTH_SHORT).show();
// Loop through paired devices
for (BluetoothDevice device : pairedDevices) {
// Add the name and address to an array adapter to show in a ListView
String s = " ";
String deviceName = device.getName();
String deviceAddress = device.getAddress();
pairedDevicesList.add(deviceName + s + deviceAddress +" \n");
//listView.setAdapter(mArrayAdapter);
//Toast.makeText(getApplicationContext(), device.getName(),Toast.LENGTH_SHORT).show();
}
/*
mArrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,pairedDevicesList);
listView.setAdapter(mArrayAdapter);*/
}
}
public void displayDetectedDevices(){
mBluetoothAdapter.startDiscovery();
// Create a BroadcastReceiver for ACTION_FOUND
mReceiver = new BroadcastReceiver() {
@SuppressWarnings("static-access")
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
/* Debugging help
Toast.makeText(getApplicationContext(),action,Toast.LENGTH_SHORT).show();*/
// When discovery finds a device
if(BluetoothDevice.ACTION_FOUND.equals(action)){
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
/* Debugging help
Toast.makeText(getApplicationContext(),device.getName(),Toast.LENGTH_SHORT).show();*/
String deviceName = device.getName();
String deviceAddress = device.getAddress();
String s = " ";
unpairedDevices.add(deviceName + s + deviceAddress +" \n");
//unpairedDevicesList.add(deviceName + s + deviceAddress +" (un-paired)\n");
unpairedDevicesList = new ArrayList<String>(unpairedDevices);
}
}
};
/*adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,unpairedDevicesList);
listView.setAdapter(adapter);*/
// Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy
//Toast.makeText(getApplicationContext(), unpairedDevicesList.toString(), Toast.LENGTH_LONG).show();
}
public void makeDicoverable(int option){
Intent discoverableIntent;
if (option == 1){
discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,120);
startActivity(discoverableIntent);
Toast.makeText(getApplicationContext(), "Open discovery for 2mins", Toast.LENGTH_SHORT).show();
} else {
discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 1);
startActivity(discoverableIntent);
Toast.makeText(getApplicationContext(), "Open discovery is OFF!", Toast.LENGTH_SHORT).show();
}
}
/*Un-used Method
public void compareAddress(BluetoothDevice checkDevice,String address){
if((checkDevice.getAddress().equals(address))){
selectedDevice = checkDevice;
}
}*/
@SuppressLint("NewApi")
public class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
BluetoothSocket tmp = null;
mmDevice = device;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
// MY_UUID is the app's UUID string, also used by the server code
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) { }
mmSocket = tmp;
}
public void run() {
// Cancel discovery because it will slow down the connection
mBluetoothAdapter.cancelDiscovery();
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
try {
mmSocket.close();
} catch (IOException closeException) {
Toast.makeText(getApplicationContext(), "Connecting to device failed!", Toast.LENGTH_LONG).show();
}
return;
}
// Do work to manage the connection (in a separate thread)
mHandler.obtainMessage(SUCCESS_CONNECT, mmSocket).sendToTarget();
}
/** Will cancel an in-progress connection, and close the socket */
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) { }
}
}
}
答案 0 :(得分:0)
如果您的设备是“蓝牙到UART转换器”模块,那么,在模块上进行环回连接(即使用RXD进行短TXD)。将测试字符串从您的应用程序发送到模块,并期望收回它。根据此类测试的结果,您的应用程序或/和模块可以进一步探测,以恢复真正的问题,如果有的话。