标签:
1.蓝牙(Bluetooth)
2.与蓝牙相关的API
1.BluetoothAdapter:该类对象表示本地的蓝牙适配器
2.BluetoothDevice:代表了一个远程的Bluetooth设备
注意:需要在android3.0以上版本才可以使用
3.设置相关的权限
在清单文件中声明蓝牙的权限:<uses-permission android:name="android.permission.BLUETOOTH"/>
4.代码步骤:
public class BluetoothDemoActivity extends Activity { /** Called when the activity is first created. */ private Button bt=null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); bt=(Button)findViewById(R.id.bt); bt.setOnClickListener(new OnClickListener( ) { public void onClick(View v) { //监听“搜索配对的蓝牙”按钮 /* 先在清单文件里添加权限 * 1.新建BluetoothAdapter对象 * 2.判断蓝牙设备是否存在 * 3.判断蓝牙是否打开 * 4.获取周围的蓝牙设备(BluetoothDriver) * */ //1.创建本地蓝牙适配器 BluetoothAdapter adapter=BluetoothAdapter.getDefaultAdapter(); //2.判断是否存在蓝牙设备 if(adapter!=null) { //3.判断是否打开,还没打开的,用intent启动 if(!adapter.isEnabled()) { Intent intent= new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(intent, 0);; } //4.查找已经配对的的蓝牙设备(注意:是已配对) Set<BluetoothDevice> ds=adapter.getBondedDevices(); //遍历出来蓝牙设备, if(ds.size()>0) { for(BluetoothDevice d:ds) System.out.println("配对的蓝牙设备:"+d.getAddress()); } } else System.out.println("手机上没有蓝牙设备"); } }); } }
5.蓝牙可见性(可被其他蓝牙扫描检测)
设置可见性:需要在清单文件中加入权限<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>获取管理蓝牙权限。
//设置可见性监听器(本地蓝牙扫描可见) private class DiscoverBluetooth implements View.OnClickListener{ public void onClick(View v) { /* * 1.新建一个“蓝牙可见性”请求的意图intent * 2.为该intent加入设置可见性持续时间 * 3.startActivity()发起请求 * */ //1.设置请求的intent Intent discoverintent=new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); //2.设置可见性时间(默认最大是300,所以设置超过300都被重设为300) discoverintent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,400 ); //3.发起请求 startActivity(discoverintent); } }
6.扫描其他的蓝牙设备(startDiscovery)
public class BluetoothDemo2Activity extends Activity { /** Called when the activity is first created. */ //获取本地蓝牙 private BluetoothAdapter badapter=BluetoothAdapter.getDefaultAdapter(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //注册broadcastreceiver,最后别忘了在Activity的destroy方法里 //unregisterReceiver(bluetoothReceiver); IntentFilter intentfilter=new IntentFilter(BluetoothDevice.ACTION_FOUND); registerReceiver(bluetoothReceiver,intentfilter); } //启动“扫描蓝牙"按钮监听器 private class ScanBluetoothDevice implements View.OnClickListener { public void onClick(View v) { // 启动扫描! badapter.startDiscovery(); } } //处理扫描的请求 private BroadcastReceiver bluetoothReceiver=new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // 在此处理发起的请求 String action = intent.getAction(); if(BluetoothDevice.ACTION_FOUND.equals(action)){ //可以从收到的Intent对象当中,将代表远程蓝牙适配器的对象取出 BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); System.out.println(device.getAddress()); } } }; }
标签:
原文地址:http://www.cnblogs.com/beyondbycyx/p/4297539.html