目標:構建一個Android應用程序,用於發現範圍內BT設備的名稱和地址並將其值提交給web服務。 BT設備以前沒有被綁定到主機設備,我只是想在我走過的時候輪詢一切。Android中的藍牙設備發現 - startDiscovery()
我所做的:
- 看了又看文檔。
- 實施主機設備的BT適配器的本地實例。
- 如果未啓用,則實施通知以啓用BT。
- 註冊廣播接收器和意圖解析
ACTION_FOUNDs
來自startDiscovery()。 - 註冊BLUETOOTH和BLUETOOTH_ADMIN清單中的權限。
事情工作(如增量控制檯日誌記錄測試)直到startDiscovery()
。
無奈:
- startDiscovery() - 我懷疑我傳遞這在錯誤的上下文。這種方法需要放在什麼上下文才能正常工作?
如果你已經能夠得到這個方法的工作,我會非常感謝你的智慧。
UPDATE - 這是簡化版本的代碼,這讓我很悲傷;這種簡化重演了我的錯誤。此代碼運行,它不會拋出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;
/** Called when the activity is first created. */
@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()'運行不正常。 –