本文介绍Android中蓝牙的基本操作
- 检测本地是否有蓝牙设备
- 获取远程蓝牙设备的地址
MainActivity中一个Button,单击Button打开蓝牙设备
package com.zhoucj.bluetooh; import 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.util.Log; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class MainActivity extends Activity { private Button blueBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); blueBtn=(Button)findViewById(R.id.open_bluetooh); blueBtn.setOnClickListener(listener); } private OnClickListener listener=new OnClickListener() { @Override public void onClick(View arg0) { //得到本地蓝牙设备 BluetoothAdapter adapter=BluetoothAdapter.getDefaultAdapter(); //判断BluetoothAdapter是否为空,如果为空,则表明本机没有蓝牙设备 if(adapter!=null) { Log.i("msg", "本机应有蓝牙设备"); //调用isEnable方法,判断蓝牙是否可用 if(!adapter.isEnabled()) { //创建一个Intent对象,启动Activity,提示用户开启蓝牙设备 Intent intent=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivity(intent); } //得到所有已经配对的蓝牙适配器 Set<BluetoothDevice> devices= adapter.getBondedDevices(); if(devices.size()>0) { for (Iterator iterator = devices.iterator(); iterator.hasNext();) { BluetoothDevice bluetoothDevice = (BluetoothDevice) iterator .next(); BluetoothDevice blueDevice=(BluetoothDevice)iterator.next(); //得到远程蓝牙的名称 和 地址 Log.i("msg", blueDevice.getName()+"---"+blueDevice.getAddress()); } } }else { Log.i("msg", "没有蓝牙设备"); } } }; @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
最后记得加上
<uses-permission android:name="android.permission.BLUETOOTH" />