编程启用蓝牙在Android [英] Programmatically enabling bluetooth on Android
问题描述
我试图确定编程实现在Android蓝牙preferred方式。我发现以下任一技术工作(至少在Android 4.0.4 ...):
I'm trying to determine the preferred way for programmatically enabling bluetooth on Android. I've found that either of the following techniques works (at least on 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许可)事先给用户。是一个或另一个旧/过时的和/或一种技术仅适用于某些设备?或者是它只是一个以我个人的使用preference的事?
The former asks the user for permission prior to enabling while the latter just silently enables bluetooth (but requires the "android.permission.BLUETOOTH_ADMIN" permission). Is one or the other old/obsolete and/or is one technique only available on some devices? or is it just a matter of personal preference as to which I use?
推荐答案
这显然是在Android中的文件
It is clearly mentioned in Android Doc
蓝牙不应该没有直接的用户同意的情况下启用。如果你想以创建无线连接开启蓝牙,你应该使用ACTION_REQUEST_ENABLE意图,这将提高该请求的用户权限打开蓝牙的对话框。仅对于包括一个用户接口,用于改变系统设置,例如功率管理器的应用程序的应用程序所提供的启用()方法
Bluetooth should never be enabled without direct user consent. If you want to turn on Bluetooth in order to create a wireless connection, you should use the ACTION_REQUEST_ENABLE Intent, which will raise a dialog that requests user permission to turn on Bluetooth. The enable() method is provided only for applications that include a user interface for changing system settings, such as a "power manager" app.
这两种技术是可行的。您有权选择根据您的目的和要求。
希望它回答你的问题。
Both of these techniques would work. You have to choose based on your purpose and requirement. Hope it answers your questions.
这篇关于编程启用蓝牙在Android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!