蓝牙的开启:蓝牙的开启需要用到BluetoothAdapter蓝牙适配器,通过蓝牙适配器的返回值判断系统是否支持蓝牙的使用,然后通过BluetoothAdapter的isEnable()方法判断蓝牙的使用状态,开启蓝牙;
蓝牙的开启有两种方式,第一种是使用系统对话框,第二种是静默的开启方式。
第一种开启方式需要添加的蓝牙权限:
<!--调用系统对话框启动蓝牙需要添加的权限--> <uses-permission android:name="android.permission.BLUETOOTH"/> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
添加完权限后,在onCreate方法中实例化BluetoothAdapter蓝牙适配器,通过蓝牙适配器的返回值判断系统是否支持蓝牙的使用;接着在onStart方法中采用系统对话框的方式开启蓝牙,采用startActivityForResult方法,所以在onActivityResult方法中处理开启后的结果,这里采用吐司提醒处理,代码如下所示:
public class MainActivity extends AppCompatActivity { private static final String TAG = "bluetooth"; private BluetoothAdapter mBluetoothAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //判断设备是否支持蓝牙 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if(mBluetoothAdapter == null){ Log.e(TAG, "Device not support bluetooth" ); }else{ Toast.makeText(this, "手机支持蓝牙设备!", Toast.LENGTH_SHORT).show(); } } //调用系统对话框开启蓝牙 @Override protected void onStart() { super.onStart(); if(!mBluetoothAdapter.isEnabled()){ //向系统请求开启蓝牙 Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableIntent,10); }else{ //已经开启蓝牙 Toast.makeText(this, "蓝牙已经开启", Toast.LENGTH_SHORT).show(); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(requestCode ==