我是 Android 的新手,我正在尝试测试 Android 4.3 的新蓝牙 LE 功能。我已经按照在 Android 网站上找到的文档进行了操作。但我在实际启动我的代码时遇到了一个绊脚石。
我想简单地使用一个按钮来调用我的 scanLeDevice 代码,但我看不到任何可以让我简单地做到这一点的东西。从字面上看,我所拥有的只是这个类和他们在你创建一个新项目时制作的示例 hello word 应用程序。
谁能帮我这个?我知道这很愚蠢,但我真的很难过。
作为参考,我的蓝牙类是这样的:
public class DeviceScanActivity extends ListActivity {
private BluetoothAdapter mBluetoothAdapter;
private boolean mScanning;
private Handler mHandler;
// Stops scanning after 10 seconds.
private static final long SCAN_PERIOD = 10000;
private ArrayAdapter<Object> list;
private Handler handler = new Handler();
protected void OnCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
list = new ArrayAdapter<Object>(getApplicationContext(), android.R.layout.simple_list_item_1);
setListAdapter(list);
scanLeDevice(true);
}
@TargetApi(18)
public void scanLeDevice(final boolean enable) {
list.add("Scanning...");
final BluetoothAdapter adapter = getBluetoothAdapter();
if (enable) {
// Stops scanning after a pre-defined scan period.
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
mScanning = false;
// mBluetoothAdapter.stopLeScan(mLeScanCallback);
adapter.stopLeScan(callback);
list.clear();
}
}, SCAN_PERIOD);
mScanning = true;
adapter.startLeScan(callback);
} else {
mScanning = false;
adapter.stopLeScan(callback);
}
}
@TargetApi(18)
private BluetoothAdapter getBluetoothAdapter()
{
BluetoothManager manager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
return manager.getAdapter();
}
private final BluetoothAdapter.LeScanCallback callback = new BluetoothAdapter.LeScanCallback()
{
@Override
public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
// TODO Auto-generated method stub
{
list.add("found: " + device);
runOnUiThread(new Runnable(){
@Override
public void run()
{
list.add(device);
list.notifyDataSetChanged();
}
});
}
}
};
}