Android에서 프로그래밍 방식으로 블루투스를 활성화 / 비활성화하는 방법
프로그램을 통해 블루투스를 활성화 / 비활성화하고 싶습니다. 다음 코드가 있습니다.
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
그러나이 코드는 SDK 1.5에서 작동하지 않습니다. 어떻게 작동시킬 수 있습니까?
Android BluetoothAdapter 문서에 따르면 API 레벨 5부터 사용할 수 있습니다. API 레벨 5 는 Android 2.0입니다.
Bluetooth API의 백 포트를 사용해 볼 수 있습니다 (개인적으로 시도하지 않음) : http://code.google.com/p/backport-android-bluetooth/
이 코드는 나를 위해 일했습니다 ..
//Disable bluetooth
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.disable();
}
이 작업을 수행하려면 다음 권한이 있어야합니다.
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
다음은이 작업을 수행하는 좀 더 강력한 방법이며 enable()\disable()
메서드 의 반환 값도 처리합니다 .
public static boolean setBluetooth(boolean enable) {
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
boolean isEnabled = bluetoothAdapter.isEnabled();
if (enable && !isEnabled) {
return bluetoothAdapter.enable();
}
else if(!enable && isEnabled) {
return bluetoothAdapter.disable();
}
// No need to change bluetooth state
return true;
}
그리고 매니페스트 파일에 다음 권한을 추가합니다.
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
그러나 다음과 같은 중요한 사항을 기억하십시오.
이것은 비동기 호출입니다. 즉시 반환되며 클라이언트는 ACTION_STATE_CHANGED를 수신하여 후속 어댑터 상태 변경에 대한 알림을 받아야합니다. 이 호출이 true를 반환하면 어댑터 상태는 즉시 STATE_OFF에서 STATE_TURNING_ON으로 전환되고 잠시 후에 STATE_OFF 또는 STATE_ON으로 전환됩니다. 이 호출이 false를 반환하면 비행기 모드와 같이 어댑터를 켤 수없는 즉각적인 문제가 있거나 어댑터가 이미 켜져있는 것입니다.
최신 정보:
좋아, 블루투스 수신기를 구현하는 방법은 무엇입니까? :
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
BluetoothAdapter.ERROR);
switch (state) {
case BluetoothAdapter.STATE_OFF:
// Bluetooth has been turned off;
break;
case BluetoothAdapter.STATE_TURNING_OFF:
// Bluetooth is turning off;
break;
case BluetoothAdapter.STATE_ON:
// Bluetooth has been on
break;
case BluetoothAdapter.STATE_TURNING_ON:
// Bluetooth is turning on
break;
}
}
}
};
수신기를 등록 / 등록 해제하는 방법은 무엇입니까? ( Activity
반에서)
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ...
// Register for broadcasts on BluetoothAdapter state change
IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mReceiver, filter);
}
@Override
public void onStop() {
super.onStop();
// ...
// Unregister broadcast listeners
unregisterReceiver(mReceiver);
}
Bluetooth를 활성화하려면 다음 기능 중 하나를 사용할 수 있습니다.
public void enableBT(View view){
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (!mBluetoothAdapter.isEnabled()){
Intent intentBtEnabled = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
// The REQUEST_ENABLE_BT constant passed to startActivityForResult() is a locally defined integer (which must be greater than 0), that the system passes back to you in your onActivityResult()
// implementation as the requestCode parameter.
int REQUEST_ENABLE_BT = 1;
startActivityForResult(intentBtEnabled, REQUEST_ENABLE_BT);
}
}
두 번째 기능은 다음과 같습니다.
public void enableBT(View view){
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (!mBluetoothAdapter.isEnabled()){
mBluetoothAdapter.enable();
}
}
The difference is that the first function makes the app ask the user a permission to turn on the Bluetooth or to deny. The second function makes the app turn on the Bluetooth directly.
To Disable the Bluetooth use the following function:
public void disableBT(View view){
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter.isEnabled()){
mBluetoothAdapter.disable();
}
}
NOTE/ The first function needs only the following permission to be defined in the AndroidManifest.xml file:
<uses-permission android:name="android.permission.BLUETOOTH"/>
While, the second and third functions need the following permissions:
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
The solution of prijin worked perfectly for me. It is just fair to mention that two additional permissions are needed:
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
When these are added, enabling and disabling works flawless with the default bluetooth adapter.
I used the below code to disable BT when my app launches and works fine. Not sure if this the correct way to implement this as google recommends not using "bluetooth.disable();" without explicit user action to turn off Bluetooth.
BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
bluetooth.disable();
I only used the below permission.
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
Add the following permissions into your manifest file:
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
Enable bluetooth use this
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (!mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.enable();
}else{Toast.makeText(getApplicationContext(), "Bluetooth Al-Ready Enable", Toast.LENGTH_LONG).show();}
Disable bluetooth use this
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.disable();
}
try this:
//this method to check bluetooth is enable or not: true if enable, false is not enable
public static boolean isBluetoothEnabled()
{
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (!mBluetoothAdapter.isEnabled()) {
// Bluetooth is not enable :)
return false;
}
else{
return true;
}
}
//method to enable bluetooth
public static void enableBluetooth(){
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (!mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.enable();
}
}
//method to disable bluetooth
public static void disableBluetooth(){
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.disable();
}
}
Add these permissions in manifest
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
'Programing' 카테고리의 다른 글
PowerShell : 전체 텍스트 파일 내용을 변수에 저장 (0) | 2020.08.18 |
---|---|
Android에서 현재 메모리 사용량을 얻는 방법은 무엇입니까? (0) | 2020.08.18 |
UILabel 줄 간격 설정 (0) | 2020.08.18 |
jQuery scroll () 사용자가 스크롤을 중지 할 때 감지 (0) | 2020.08.18 |
간단한 jQuery 양식 유효성 검사 스크립트 (0) | 2020.08.18 |