目标:建構一個Android應用程式,發現範圍内BT裝置的名稱和位址,并将其值送出給Web服務。 以前沒有将BT裝置綁定到主機裝置上,我隻想在我走動時檢視所有内容。
我做了什麼:仔細閱讀文檔。
實作了主機裝置的BT擴充卡的本地執行個體。
如果未啟用BT,則實施啟用BT的通知。
注冊的廣播接收者和意圖來解析startDiscovery()的ACTION_FOUND 。
清單中注冊的BLUETOOTH和BLUETOOTH_ADMIN權限。
在startDiscovery()之前一切正常(通過增量控制台日志記錄測試startDiscovery() 。
挫折:
startDiscovery() – 我懷疑我在錯誤的上下文中傳遞了這個。 該方法需要在什麼上下文中才能正常運作?
如果你能夠使用這種方法,我将非常感謝你的智慧。
更新 – 這是一個簡化的代碼簡化版本,讓我感到悲傷; 這種簡化概括了我的錯誤。 這段代碼運作,它不會抛出cat.log錯誤或其他錯誤,它根本不提供任何輸出。
package aqu.bttest; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.widget.Toast; public class BT2Activity extends Activity { private BluetoothAdapter mBTA; private SingBroadcastReceiver mReceiver; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //register local BT adapter mBTA = BluetoothAdapter.getDefaultAdapter(); //check to see if there is BT on the Android device at all if (mBTA == null){ int duration = Toast.LENGTH_SHORT; Toast.makeText(this, "No Bluetooth on this handset", duration).show(); } //let's make the user enable BT if it isn't already if (!mBTA.isEnabled()){ Intent enableBT = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBT, 0xDEADBEEF); } //cancel any prior BT device discovery if (mBTA.isDiscovering()){ mBTA.cancelDiscovery(); } //re-start discovery mBTA.startDiscovery(); //let's make a broadcast receiver to register our things mReceiver = new SingBroadcastReceiver(); IntentFilter ifilter = new IntentFilter(BluetoothDevice.ACTION_FOUND); this.registerReceiver(mReceiver, ifilter); } private class SingBroadcastReceiver extends BroadcastReceiver { public void onReceive(Context context, Intent intent) { String action = intent.getAction(); //may need to chain this to a recognizing function 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 Toast String derp = device.getName() + " - " + device.getAddress(); Toast.makeText(context, derp, Toast.LENGTH_LONG); } } }
}
該方法需要在什麼上下文中才能正常運作。
簡單地說,當你希望你的應用程式發現本地藍牙裝置時,你應該使用startDiscovery() …例如,如果你想實作一個ListActivity來掃描并動态地将附近的藍牙裝置添加到ListView (參見DeviceListActivity )。
您對startDiscovery()方法的使用應如下所示:
定義表示本地藍牙擴充卡的類variables。
BluetoothAdapter mBtAdapter = BluetoothAdapter.getDefaultAdapter();
檢查您的裝置是否已“發現”。 如果是,則取消發現。
if (mBtAdapter.isDiscovering()) { mBtAdapter.cancelDiscovery(); }
在檢查(并可能取消)發現模式後,立即通過調用開始發現,
mBtAdapter.startDiscovery();
一般要非常小心,不小心将裝置置于發現模式。 執行裝置發現對于藍牙擴充卡來說是一個繁重的過程,并且會消耗大量資源。 例如,您要確定在嘗試建立連接配接之前檢查/取消發現。 您很可能也希望在onDestroy方法中取消發現。
如果這有幫助,請告訴我…如果您仍然遇到問題,請使用您的logcat輸出和/或您收到的任何錯誤消息更新您的答案,也許我可以幫助您更多。