android之蓝牙操作(一)
与蓝牙相关的API
1、BluetoothAdapter
该类的对象代表了本地的蓝牙适配器
2、BluetoothDevice
该类的对象代表了远程的蓝牙适配器
扫描已经配对的蓝牙设备步骤:
1、获得BluetoothAdapter对象
2、判断当前的设备中是否有蓝牙设备
3、判断当前设备中的蓝牙设备是否已经打开
4、得到所以已经配对的蓝牙设备对象
在AndroidManifedt.xml中声明蓝牙权限
在布局文件中添加一个按钮
main.xml
MainActivity.javaimport java.util.Iterator;import java.util.Set;import android.app.Activity;import android.bluetooth.BluetoothAdapter;import android.bluetooth.BluetoothDevice;import android.content.Intent;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;public class TestBluetoothActivity extends Activity { /** Called when the activity is first created. */private Button button = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); button = (Button)findViewById(R.id.button); button.setOnClickListener(new ButtonListener()); } private class ButtonListener implements OnClickListener {@Overridepublic void onClick(View v) {// TODO Auto-generated method stub//得到BluetoothAdapter对象BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();//判断BluetoothAdapter对象是否为空,若为空,则本机上无蓝牙设备if (bluetoothAdapter != null) {System.out.println("本机上拥有蓝牙设备");if (!bluetoothAdapter.enable()) {//创建一个Intent对象,该对象用来启动另外一个Activity,提示用户启动蓝牙设备Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);startActivity(intent);}//得到所有已经匹配的蓝牙适配器对象Set<BluetoothDevice> device = bluetoothAdapter.getBondedDevices();if (device.size()>0) {for (Iterator iterator = device.iterator(); iterator.hasNext();) {BluetoothDevice bluetoothDevice = (BluetoothDevice) iterator.next();System.out.println(bluetoothDevice.getAddress());}}}else {System.out.println("本机上无蓝牙设备");}} }}