android 蓝牙 获取蓝牙地址名字

蓝牙是一种支持设备之间短距离通讯的无限电技术(电话,笔记本,耳机)

BluetoothAdapter 本地蓝牙适配器

首先需要添加蓝牙权限:

 
  
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
然后再acitivity
//获取本地蓝牙的适配器
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
 
  
//判断蓝牙功能是否存在
if (mBluetoothAdapter == null) {
showToest("该设备不支持蓝牙");
return;
}
 
  
//获取名字 MAC地址
String name = mBluetoothAdapter.getName();
String address = mBluetoothAdapter.getAddress();
Log.i(TAG, "蓝牙名: "+name+"mac地址:"+address);
//获取蓝牙的状态
int state = mBluetoothAdapter.getState();
switch (state){
case BluetoothAdapter.STATE_ON:
showToest("蓝牙已经打开");
Log.i(TAG, "蓝牙已经打开 ");
break;
case BluetoothAdapter.STATE_OFF:
showToest("蓝牙已经关闭");
Log.i(TAG, "蓝牙已经关闭 ");
break;
case BluetoothAdapter.STATE_TURNING_OFF:
showToest("蓝牙正在关闭");
Log.i(TAG, "蓝牙正在关闭 ");
break;
case BluetoothAdapter.STATE_TURNING_ON:
showToest("蓝牙正在打开");
Log.i(TAG, "蓝牙正在打开 ");
break;
default:
break;
}
 
  
//判断蓝牙是否已经打开
if (mBluetoothAdapter.isEnabled()){
showToest("蓝牙已经处于打开状态");
//关闭蓝牙
Boolean isClose=mBluetoothAdapter.disable();
Log.i(TAG, "蓝牙是否关闭"+isClose);
}else{
// Boolean isopen = mBluetoothAdapter.enable();
// showToest("蓝牙的状态"+isopen);
//调用系统API打开
Intent intent=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent,RESULE_OPEN);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(RESULE_OPEN==0x01){
         if(resultCode==RESULT_CANCELED){
             showToest("请求失败");
         }else{
             showToest("请求成功...");
         }
    }
}

public void  showToest(String mgs){
    Toast.makeText(MainActivity.this,mgs,Toast.LENGTH_LONG).show();
}

你可能感兴趣的:(android,l)