我是Android的新手,我试图测试Android 4.3的新蓝牙LE功能。我已按照here on the Android site找到的文档进行操作。但我正处于实际启动代码的绊脚石。
我想的只是有一个叫做scanLeDevice代码的按钮,但我看不到任何可以让我这么做的事情。我所拥有的只是这个类以及他们在制作新项目时制作的示例hello word app。
任何人都可以帮我吗?我知道它是愚蠢的,但我真的很难过。
作为参考,我的蓝牙课程是这样的:
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();
}
});
}
}
};
}
答案 0 :(得分:0)
在MainActivity中添加一个新按钮:
<Button
android:id="@+id/btnCallMethod"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Call Method" />
将它放在MainActivity的onCreate()
中addListeners();
这就是addListeners()方法在MainActivity中的样子:
private void addListeners() {
Button btnCallMethod = (Button) this.findViewById(R.id.btnCallMethod);
// CALL METHOD BUTTON
btnCallMethod.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
Intent intent = new Intent(getApplicationContext(), DeviceScanActivity.class);
startActivity(intent); // start the DeciveScanActivity
}
return false;
}
});
}
现在在DeviceScanActivity的onCreate()方法中调用该方法
不要忘记将DeviceScanActivity添加到AndroidManifest.xml
<activity
android:name="com.example.example.DeviceScanActivity"
</activity>