我是 Android 编程新手,现在遇到了问题。我想将我的 android 手机用作蓝牙服务器,这意味着当我打开一个特殊的 Activity 时,手机应该听其他蓝牙设备(已经配对)并且其他设备可以打开我的 android 手机的连接。所以它应该就像手机是一个外围设备,就像一个bt扬声器。所以配对仍然完成。并发现我必须使用 SPP 模式。当它连接时,我想发送一个接收简单的字节流。我找到了一个名为“bluetooth spp tools pro”(https://play.google.com/store/apps/details?id=mobi.dzs.android.BLE_SPP_PRO&hl=de)的应用程序,它几乎可以满足我的所有需求。但这里的问题是手机作为客户端工作并打开连接。
所以也许你可以帮助我,给我一些提示来理解我必须做什么。
谢谢您的帮助:)
编辑:现在我尝试了一个来自 Android 的示例,它似乎几乎可以工作了。我可以将我的电脑与智能手机连接,然后智能手机与之连接。但是当它连接时,应用程序崩溃了,我不知道为什么......也许你可以告诉我为什么 ma 应用程序崩溃......这里的代码:
public class BluetoothServer extends AppCompatActivity {
public BluetoothAdapter mBluetoothAdapter;
private static final UUID MY_UUID_SECURE = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private AcceptThread mSecureAcceptThread;
private TextView textViewStatus;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bluetooth_server);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
textViewStatus = (TextView) findViewById(R.id.BluetoothServerTextView);
}
@Override
protected void onDestroy() {
super.onDestroy();
mSecureAcceptThread.cancel();
mSecureAcceptThread = null;
}
public void onClickOpenBluetoothServer(View view) {
// Setup Bluetooth Adapter
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
//Enable Discoverbility
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
textViewStatus.append("\nDiscoverable Added!");
//Starting Accepting Thread
mSecureAcceptThread = new AcceptThread();
mSecureAcceptThread.start();
}
/**
* Accepting Thread mit run();
*/
private class AcceptThread extends Thread {
private final BluetoothServerSocket mmServerSocket;
public AcceptThread() {
BluetoothServerSocket tmp = null;
try {
// MY_UUID is the app's UUID string, also used by the client code
tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord("PAKSAFE", MY_UUID_SECURE);
} catch (IOException e) { }
mmServerSocket = tmp;
textViewStatus.append("\nAcceptThread Created!");
}
public void run() {
BluetoothSocket socket = null;
// Keep listening until exception occurs or a socket is returned
while (true) {
try {
textViewStatus.append("\nListening");
socket = mmServerSocket.accept();
} catch (IOException e) {
break;
}
// If a connection was accepted
if (socket != null) {
// Do work to manage the connection (in a separate thread)
//manageConnectedSocket(socket);
textViewStatus.setText("Acccepted");
try {
mmServerSocket.close();
} catch (IOException e) {
break;
}
break;
}
}
}
/** Will cancel the listening socket, and cause the thread to finish */
public void cancel() {
try {
mmServerSocket.close();
} catch (IOException e) { }
}
}
}