我想确定在Android上以编程方式启用蓝牙的首选方法。 我发现以下两种技术均可使用(至少在Android 4.0.4上):
public class MyActivity extends Activity {
public static final int MY_BLUETOOTH_ENABLE_REQUEST_ID = 6;
...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, MY_BLUETOOTH_ENABLE_REQUEST_ID);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == MY_BLUETOOTH_ENABLE_REQUEST_ID) {
if (resultCode == RESULT_OK) {
// Request granted - bluetooth is turning on...
}
if (resultCode == RESULT_CANCELED) {
// Request denied by user, or an error was encountered while
// attempting to enable bluetooth
}
}
}
或者说……
BluetoothAdapter.getDefaultAdapter().enable();
前者在启用之前向用户请求权限,而后者只是默默地启用蓝牙(但需要"android.permission.BLUETOOTH_ADMIN"权限)。其中一个或另一个已经老旧/过时了吗?还是有些设备只支持其中一种技术?或者只是个人喜好决定我使用哪种?