2012-02-24 165 views
1

我正在開發藍牙聊天應用程序。問題是,當我啓用藍牙應用程序啓用藍牙,但導致強制關閉。下一次我啓動相同的應用程序(啓用藍牙),它工作順利!我已經搜查,只得到了一些資料說,當我開始故意對啓用藍牙的代碼進行不等待意向的結果Android藍牙啓用

 public void run() { 

     // 1. Check if Bluetooth is Enabled 
     if (!blue.isEnabled()) { 
      Intent enable_Bluetooth = new Intent(
        BluetoothAdapter.ACTION_REQUEST_ENABLE); 
      startActivityForResult(enable_Bluetooth, 1); 

     } 

     // 2. Start Bluetooth Server 
     try { 
      Server = blue.listenUsingRfcommWithServiceRecord("dhiraj", 
        MY_UUID); 
+0

DHIRAJ,安卓自帶樣品藍牙聊天應用。在實施你的應用之前,你應該仔細研究它。查看連接部分的鏈接,分析出錯的地方; http://developer.android.com/resources/samples/BluetoothChat/src/com/example/android/BluetoothChat/BluetoothChat.html – AnCoder 2012-02-24 06:13:56

回答

8

第一:

聲明藍牙權限(S)在你的應用清單文件。 例如:

<manifest ... > 
<uses-permission android:name="android.permission.BLUETOOTH" /> 
... 
</manifest> 

設置藍牙:

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 
if (mBluetoothAdapter == null) { 
// Device does not support Bluetooth 
} 

啓用藍牙:

if (!mBluetoothAdapter.isEnabled()) { 
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); 
} 

查找設備:

Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices(); 
// If there are paired devices 
if (pairedDevices.size() > 0) { 
// Loop through paired devices 
for (BluetoothDevice device : pairedDevices) { 
    // Add the name and address to an array adapter to show in a ListView 
    mArrayAdapter.add(device.getName() + "\n" + device.getAddress()); 
} 
} 

發現設備:

// Create a BroadcastReceiver for ACTION_FOUND 
private final BroadcastReceiver mReceiver = new BroadcastReceiver() { 
@Override public void onReceive(Context context, Intent intent) { 
    String action = intent.getAction(); 
    // When discovery finds a device 
    if (BluetoothDevice.ACTION_FOUND.equals(action)) { 
     // Get the BluetoothDevice object from the Intent 
     BluetoothDevice device =  
intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 
     // Add the name and address to an array adapter to show in a ListView 
     mArrayAdapter.add(device.getName() + "\n" + device.getAddress()); 
    } 
} 
}; 
// Register the BroadcastReceiver 
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); 
registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy 

啓用發現

Intent discoverableIntent = new 
Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); 
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300); 
startActivity(discoverableIntent); 
+0

我不知道startActivityforReult()的第二個參數'int'是做什麼的? – 2012-03-16 12:19:18

+0

發現錯誤!它發生的真正原因是後臺代碼用戶調用藍牙ServerSocket.accept()甚至在藍牙開始之前調用...我只是把一個循環(!正在運行){//等待藍牙啓用}它的工作...沒有力量關閉 – 2012-03-18 01:15:10

+0

雖然啓用藍牙,startActivityForResult()的第二個參數不被接受。我是否需要添加其他聲明?..在遵循TutorialsPoint的教程之後,我嘗試了傳遞0作爲第二個參數。沒有顯示任何錯誤,但在我的手機上運行它,程序無法啓動。 – 20B2 2017-06-08 02:40:41