0

I am writing my first mobile app on Android Studio Electric EEl (2022.1.1 Patch 2).

For my first app, I would like to develop a simple checkbox that allows user to toggle the Bluetooth ON/OFF. The project can be accessed here if: https://github.com/krupis/BLE_test_app

I have pretty much followed the tutorial by Android Codelab on youtube, just with changed some variable names and other small things: https://www.youtube.com/watch?v=oZKd6gpMKQg&ab_channel=AndroidCodelab

My AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.ble_app">

    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.BLUETOOTH_CONNECT"/>
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>


    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/Theme.Ble_app"
        tools:targetApi="31">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

My MainActivity.java

package com.example.ble_app;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private BluetoothAdapter BA;
    int REQUEST_ENABLE_BLUETOOTH = 0;

    CheckBox btCheckbox;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        btCheckbox = findViewById(R.id.btCheckbox);
        BA = BluetoothAdapter.getDefaultAdapter();
        setListeners();

    }





    private void setListeners(){
        btCheckbox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //IF CHECKBOX CHECKED
                if (((CompoundButton) view).isChecked()) {
                    System.out.println("Checked");
                    if (BA == null) {
                        Toast.makeText(MainActivity.this, "Bluetooth not supported", Toast.LENGTH_SHORT).show();
                    }
                    else {

                        if (ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_DENIED) {
                            if (Build.VERSION.SDK_INT >= 31) {
                                ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.BLUETOOTH_CONNECT}, 100);
                                return;
                            }
                        }
                        if(!BA.isEnabled()) {
                            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                            startActivityForResult(enableIntent, REQUEST_ENABLE_BLUETOOTH);
                            Toast.makeText(MainActivity.this, "Bluetooth enabled", Toast.LENGTH_SHORT).show();
                        }
                        else{
                            Toast.makeText(MainActivity.this, "Bluetooth already enabled", Toast.LENGTH_SHORT).show();
                        }
                    }
                }
                //IF CHECKBOX UNCHECKED
                else{
                    System.out.println("UnChecked");
                    if(BA.isEnabled()){
                        System.out.println("Disabling the Bluetooth \n");
                        BA.disable();
                        Toast.makeText(MainActivity.this,"Bluetooth disabled",Toast.LENGTH_SHORT).show();
                    }
                }

            }
        });
    }




}

I have connected my physical device (Samsung Z Flip) to my PC via the USB and I am running my APP on my physical device.

When the APP is launched, I can click on the checkbox to Enable the Bluetooth. As soon as I click the button, the prompt shows up at the bottom requesting to give access to enable the Bluetooth. I click "Allow" and I can see that the Bluetooth is enabled on my phoneenter image description here

However, when I try to toggle the checkbox again (Uncheck it), I can see that the the correct lines of code are executed because I can see "Disabling the Bluetooth" being printed to Debug window. But the Bluetooth does not turn OFF after I call BA.disable() for some reason.

Debug logs:

Connected to the target VM, address: 'localhost:1065', transport: 'socket'
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
I/example.ble_app: Late-enabling -Xcheck:jni
D/ActivityThread: setConscryptValidator
D/ActivityThread: setConscryptValidator - put
V/studio.deploy: Startup agent attached to VM
V/studio.deploy: No existing instrumentation found. Loading instrumentation from instruments-a7e44b7b.jar
W/example.ble_app: DexFile /data/data/com.example.ble_app/code_cache/.studio/instruments-a7e44b7b.jar is in boot class path but is not in a known location
V/studio.deploy: Applying transforms with cached classes
W/example.ble_app: Redefining intrinsic method java.lang.Thread java.lang.Thread.currentThread(). This may cause the unexpected use of the original definition of java.lang.Thread java.lang.Thread.currentThread()in methods that have already been compiled.
W/example.ble_app: Redefining intrinsic method boolean java.lang.Thread.interrupted(). This may cause the unexpected use of the original definition of boolean java.lang.Thread.interrupted()in methods that have already been compiled.
D/CompatibilityChangeReporter: Compat change id reported: 171979766; UID 10473; state: ENABLED
W/ActivityThread: Application com.example.ble_app is waiting for the debugger on port 8100...
I/System.out: Sending WAIT chunk
I/System.out: Debugger has connected
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: debugger has settled (1479)
W/ziparchive: Unable to open '/data/data/com.example.ble_app/code_cache/.overlay/base.apk/classes3.dm': No such file or directory
W/ziparchive: Unable to open '/data/app/~~EohyBEP8hkMFuXzmBNx30Q==/com.example.ble_app--VoyTn874X5ENUFkucS7Dg==/base.dm': No such file or directory
W/ziparchive: Unable to open '/data/app/~~EohyBEP8hkMFuXzmBNx30Q==/com.example.ble_app--VoyTn874X5ENUFkucS7Dg==/base.dm': No such file or directory
D/nativeloader: Configuring classloader-namespace for other apk /data/app/~~EohyBEP8hkMFuXzmBNx30Q==/com.example.ble_app--VoyTn874X5ENUFkucS7Dg==/base.apk. target_sdk_version=33, uses_libraries=, library_path=/data/app/~~EohyBEP8hkMFuXzmBNx30Q==/com.example.ble_app--VoyTn874X5ENUFkucS7Dg==/lib/arm64, permitted_path=/data:/mnt/expand:/data/user/0/com.example.ble_app
V/GraphicsEnvironment: ANGLE Developer option for 'com.example.ble_app' set to: 'default'
V/GraphicsEnvironment: ANGLE GameManagerService for com.example.ble_app: false
V/GraphicsEnvironment: App is not on the allowlist for updatable production driver.
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
D/OpenGLRenderer: RenderThread::requireGlContext()
I/AdrenoGLES-0: QUALCOMM build                   : b8e5a4d0d5, Ib45df4a8b0
    Build Date                       : 07/11/22
    OpenGL ES Shader Compiler Version: EV031.36.08.09
    Local Branch                     : 
    Remote Branch                    : 
    Remote Branch                    : 
    Reconstruct Branch               : 
I/AdrenoGLES-0: Build Config                     : S P 12.1.1 AArch64
I/AdrenoGLES-0: Driver Path                      : /vendor/lib64/egl/libGLESv2_adreno.so
I/AdrenoGLES-0: Driver Version                   : 0615.0
I/AdrenoGLES-0: PFP: 0x01730155, ME: 0x00000000
W/Adreno-AppProfiles: Could not find QSPM HAL service. Skipping adreno profile processing.
D/OpenGLRenderer: RenderThread::setGrContext()
D/AppCompatDelegate: Checking for metadata for AppLocalesMetadataHolderService : Service not found
I/DecorView: [INFO] isPopOver=false config=true
I/DecorView: updateCaptionType: isFloating=false isApplication=true hasWindowDecorCaption=false this=DecorView@de0b2c8[]
D/DecorView: setCaptionType = 0, this = DecorView@de0b2c8[]
I/DecorView: getCurrentDensityDpi: from real metrics. densityDpi=480 msg=resources_loaded
I/DecorView: setWindowBackground: isPopOver=false color=ff121212 d=android.graphics.drawable.ColorDrawable@321ba86
W/example.ble_app: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (unsupported, reflection, allowed)
W/example.ble_app: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (unsupported, reflection, allowed)
D/CompatibilityChangeReporter: Compat change id reported: 210923482; UID 10473; state: ENABLED
I/BluetoothAdapter: BluetoothAdapter() : com.example.ble_app
I/MSHandlerLifeCycle: check: return. pkg=com.example.ble_app parent=null callers=com.android.internal.policy.DecorView.setVisibility:4401 android.app.ActivityThread.handleResumeActivity:5468 android.app.servertransaction.ResumeActivityItem.execute:54 android.app.servertransaction.ActivityTransactionItem.execute:45 android.app.servertransaction.TransactionExecutor.executeLifecycleState:176 
I/MSHandlerLifeCycle: removeMultiSplitHandler: no exist. decor=DecorView@de0b2c8[]
D/NativeCustomFrequencyManager: [NativeCFMS] BpCustomFrequencyManager::BpCustomFrequencyManager()
D/InsetsController: onStateChanged: InsetsState: {mDisplayFrame=Rect(0, 0 - 1080, 2640), mDisplayCutout=DisplayCutout{insets=Rect(0, 94 - 0, 0) waterfall=Insets{left=0, top=0, right=0, bottom=0} boundingRect={Bounds=[Rect(0, 0 - 0, 0), Rect(505, 0 - 576, 94), Rect(0, 0 - 0, 0), Rect(0, 0 - 0, 0)]} cutoutPathParserInfo={CutoutPathParserInfo{displayWidth=1080 displayHeight=2640 physicalDisplayWidth=1080 physicalDisplayHeight=2640 density={3.0} cutoutSpec={M 0,0 H -11.83333333333333 V 31.33333333333333 H 11.83333333333333 V 0 H 0 Z @dp} rotation={0} scale={1.0} physicalPixelDisplaySizeRatio={1.0}}}}, mRoundedCorners=RoundedCorners{[RoundedCorner{position=TopLeft, radius=108, center=Point(108, 108)}, RoundedCorner{position=TopRight, radius=108, center=Point(972, 108)}, RoundedCorner{position=BottomRight, radius=108, center=Point(972, 2532)}, RoundedCorner{position=BottomLeft, radius=108, center=Point(108, 2532)}]}  mRoundedCornerFrame=Rect(0, 0 - 1080, 2640), mPrivacyIndicatorBounds=PrivacyIndicatorBounds {static bounds=Rect(948, 0 - 1080, 94) rotation=0}, mSources= { InsetsSource: {mType=ITYPE_STATUS_BAR, mFrame=[0,0][1080,94], mVisible=true, mInsetsRoundedCornerFrame=false}, InsetsSource: {mType=ITYPE_NAVIGATION_BAR, mFrame=[0,2496][1080,2640], mVisible=true, mInsetsRoundedCornerFrame=false}, InsetsSource: {mType=ITYPE_LEFT_GESTURES, mFrame=[0,0][0,2640], mVisible=true, mInsetsRoundedCornerFrame=false}, InsetsSource: {mType=ITYPE_RIGHT_GESTURES, mFrame=[1080,0][1080,2640], mVisible=true, mInsetsRoundedCornerFrame=false}, InsetsSource: {mType=ITYPE_TOP_MANDATORY_GESTURES, mFrame=[0,0][1080,130], mVisible=true, mInsetsRoundedCornerFrame=false}, InsetsSource: {mType=ITYPE_BOTTOM_MANDATORY_GESTURES, mFrame=[0,2496][1080,2640], mVisible=true, mInsetsRoundedCornerFrame=false}, InsetsSource: {mType=ITYPE_LEFT_DISPLAY_CUTOUT, mFrame=[0,0][-100000,2640], mVisible=true, mInsetsRoundedCornerFrame=false}, InsetsSource: {mType=ITYPE_TOP_DISPLAY_CUTOUT, mFrame=[0,0][1080,94], mVisible=true, mInsetsRoundedCornerFrame=false}, InsetsSource: {mType=ITYPE_RIGHT_DISPLAY_CUTOUT, mFrame=[100000,0][1080,2640], mVisible=true, mInsetsRoundedCornerFrame=false}, InsetsSource: {mType=ITYPE_BOTTOM_DISPLAY_CUTOUT, mFrame=[0,100000][1080,2640], mVisible=true, mInsetsRoundedCornerFrame=false}, InsetsSource: {mType=ITYPE_TOP_TAPPABLE_ELEMENT, mFrame=[0,0][1080,94], mVisible=true, mInsetsRoundedCornerFrame=false}, InsetsSource: {mType=ITYPE_BOTTOM_TAPPABLE_ELEMENT, mFrame=[0,2496][1080,2640], mVisible=true, mInsetsRoundedCornerFrame=false} } host=com.example.ble_app/com.example.ble_app.MainActivity from=android.view.ViewRootImpl.setView:1722
I/ViewRootImpl@a08a9fe[MainActivity]: setView = com.android.internal.policy.DecorView@de0b2c8 TM=true
I/MSHandlerLifeCycle: removeMultiSplitHandler: no exist. decor=DecorView@de0b2c8[MainActivity]
D/ViewRootImpl@a08a9fe[MainActivity]: performTraversals params={(0,0)(fillxfill) sim={adjust=pan forwardNavigation} ty=BASE_APPLICATION wanim=0x1030309
      fl=81810100
      pfl=12020040
      bhv=DEFAULT
      fitSides= naviIconColor=0}
D/ViewRootImpl@a08a9fe[MainActivity]: performTraversals mFirst=true windowShouldResize=true viewVisibilityChanged=false mForceNextWindowRelayout=false params={(0,0)(fillxfill) sim={adjust=pan forwardNavigation} ty=BASE_APPLICATION wanim=0x1030309
      fl=81810100
      pfl=12020040
      bhv=DEFAULT
      fitSides= naviIconColor=0}
E/BufferQueueProducer: Unable to open libpenguin.so: dlopen failed: library "libpenguin.so" not found.
I/BLASTBufferQueue: new BLASTBufferQueue, mName= ViewRootImpl@a08a9fe[MainActivity] mNativeObject= 0xb400007ac470b730 sc.mNativeObject= 0xb400007a54730cc0 caller= android.view.ViewRootImpl.updateBlastSurfaceIfNeeded:2815 android.view.ViewRootImpl.relayoutWindow:9661 android.view.ViewRootImpl.performTraversals:3785 android.view.ViewRootImpl.doTraversal:3017 android.view.ViewRootImpl$TraversalRunnable.run:10699 android.view.Choreographer$CallbackRecord.run:1301 android.view.Choreographer$CallbackRecord.run:1309 android.view.Choreographer.doCallbacks:923 android.view.Choreographer.doFrame:852 android.view.Choreographer$FrameDisplayEventReceiver.run:1283 
I/BLASTBufferQueue: update, w= 1080 h= 2640 mName = ViewRootImpl@a08a9fe[MainActivity] mNativeObject= 0xb400007ac470b730 sc.mNativeObject= 0xb400007a54730cc0 format= -1 caller= android.graphics.BLASTBufferQueue.<init>:84 android.view.ViewRootImpl.updateBlastSurfaceIfNeeded:2815 android.view.ViewRootImpl.relayoutWindow:9661 android.view.ViewRootImpl.performTraversals:3785 android.view.ViewRootImpl.doTraversal:3017 android.view.ViewRootImpl$TraversalRunnable.run:10699 
I/ViewRootImpl@a08a9fe[MainActivity]: Relayout returned: old=(0,0,1080,2640) new=(0,0,1080,2640) req=(1080,2640)0 dur=10 res=0x3 s={true 0xb400007b5470c110} ch=true seqId=0
D/ViewRootImpl@a08a9fe[MainActivity]: mThreadedRenderer.initialize() mSurface={isValid=true 0xb400007b5470c110} hwInitialized=true
D/ViewRootImpl@a08a9fe[MainActivity]: reportNextDraw android.view.ViewRootImpl.performTraversals:4339 android.view.ViewRootImpl.doTraversal:3017 android.view.ViewRootImpl$TraversalRunnable.run:10699 android.view.Choreographer$CallbackRecord.run:1301 android.view.Choreographer$CallbackRecord.run:1309 
D/ViewRootImpl@a08a9fe[MainActivity]: Setup new sync id=0
D/ViewRootImpl@a08a9fe[MainActivity]: Setting syncFrameCallback
D/ViewRootImpl@a08a9fe[MainActivity]: registerCallbacksForSync syncBuffer=false
D/OpenGLRenderer: eglCreateWindowSurface
D/ViewRootImpl@a08a9fe[MainActivity]: Received frameDrawingCallback syncResult=0 frameNum=1.
D/ViewRootImpl@a08a9fe[MainActivity]: Setting up sync and frameCommitCallback
D/BLASTBufferQueue: [ViewRootImpl@a08a9fe[MainActivity]#0](f:0,a:0) onFrameAvailable the first frame is available
D/ViewRootImpl@a08a9fe[MainActivity]: Received frameCommittedCallback lastAttemptedDrawFrameNum=1 didProduceBuffer=true
D/OpenGLRenderer: CFMS:: SetUp Pid : 19941    Tid : 20008
W/Parcel: Expecting binder but got null!
D/ViewRootImpl@a08a9fe[MainActivity]: onSyncComplete
D/ViewRootImpl@a08a9fe[MainActivity]: setupSync seqId=0 mSyncId=0 fn=1 caller=android.view.ViewRootImpl$$ExternalSyntheticLambda11.accept:6 android.window.SurfaceSyncer.lambda$setupSync$1$android-window-SurfaceSyncer:128 android.window.SurfaceSyncer$$ExternalSyntheticLambda1.accept:8 android.window.SurfaceSyncer$SyncSet.checkIfSyncIsComplete:382 android.window.SurfaceSyncer$SyncSet.markSyncReady:359 android.window.SurfaceSyncer.markSyncReady:151 android.view.ViewRootImpl.performTraversals:4399 
D/ViewRootImpl@a08a9fe[MainActivity]: reportDrawFinished seqId=0 mSyncId=-1 fn=1 mSurfaceChangedTransaction=0xb400007a846fd450
I/ViewRootImpl@a08a9fe[MainActivity]: MSG_WINDOW_FOCUS_CHANGED 1 0
D/ViewRootImpl@a08a9fe[MainActivity]: mThreadedRenderer.initializeIfNeeded()#2 mSurface={isValid=true 0xb400007b5470c110}
D/InputMethodManager: startInputInner - Id : 0
I/InputMethodManager: startInputInner - mService.startInputOrWindowGainedFocus
D/InputMethodManager: startInputInner - Id : 0
D/InsetsController: onStateChanged: InsetsState: {mDisplayFrame=Rect(0, 0 - 1080, 2640), mDisplayCutout=DisplayCutout{insets=Rect(0, 94 - 0, 0) waterfall=Insets{left=0, top=0, right=0, bottom=0} boundingRect={Bounds=[Rect(0, 0 - 0, 0), Rect(505, 0 - 576, 94), Rect(0, 0 - 0, 0), Rect(0, 0 - 0, 0)]} cutoutPathParserInfo={CutoutPathParserInfo{displayWidth=1080 displayHeight=2640 physicalDisplayWidth=1080 physicalDisplayHeight=2640 density={3.0} cutoutSpec={M 0,0 H -11.83333333333333 V 31.33333333333333 H 11.83333333333333 V 0 H 0 Z @dp} rotation={0} scale={1.0} physicalPixelDisplaySizeRatio={1.0}}}}, mRoundedCorners=RoundedCorners{[RoundedCorner{position=TopLeft, radius=108, center=Point(108, 108)}, RoundedCorner{position=TopRight, radius=108, center=Point(972, 108)}, RoundedCorner{position=BottomRight, radius=108, center=Point(972, 2532)}, RoundedCorner{position=BottomLeft, radius=108, center=Point(108, 2532)}]}  mRoundedCornerFrame=Rect(0, 0 - 1080, 2640), mPrivacyIndicatorBounds=PrivacyIndicatorBounds {static bounds=Rect(948, 0 - 1080, 94) rotation=0}, mSources= { InsetsSource: {mType=ITYPE_STATUS_BAR, mFrame=[0,0][1080,94], mVisible=true, mInsetsRoundedCornerFrame=false}, InsetsSource: {mType=ITYPE_NAVIGATION_BAR, mFrame=[0,2496][1080,2640], mVisible=true, mInsetsRoundedCornerFrame=false}, InsetsSource: {mType=ITYPE_LEFT_GESTURES, mFrame=[0,0][0,2640], mVisible=true, mInsetsRoundedCornerFrame=false}, InsetsSource: {mType=ITYPE_RIGHT_GESTURES, mFrame=[1080,0][1080,2640], mVisible=true, mInsetsRoundedCornerFrame=false}, InsetsSource: {mType=ITYPE_TOP_MANDATORY_GESTURES, mFrame=[0,0][1080,130], mVisible=true, mInsetsRoundedCornerFrame=false}, InsetsSource: {mType=ITYPE_BOTTOM_MANDATORY_GESTURES, mFrame=[0,2496][1080,2640], mVisible=true, mInsetsRoundedCornerFrame=false}, InsetsSource: {mType=ITYPE_LEFT_DISPLAY_CUTOUT, mFrame=[0,0][-100000,2640], mVisible=true, mInsetsRoundedCornerFrame=false}, InsetsSource: {mType=ITYPE_TOP_DISPLAY_CUTOUT, mFrame=[0,0][1080,94], mVisible=true, mInsetsRoundedCornerFrame=false}, InsetsSource: {mType=ITYPE_RIGHT_DISPLAY_CUTOUT, mFrame=[100000,0][1080,2640], mVisible=true, mInsetsRoundedCornerFrame=false}, InsetsSource: {mType=ITYPE_BOTTOM_DISPLAY_CUTOUT, mFrame=[0,100000][1080,2640], mVisible=true, mInsetsRoundedCornerFrame=false}, InsetsSource: {mType=ITYPE_TOP_TAPPABLE_ELEMENT, mFrame=[0,0][1080,94], mVisible=true, mInsetsRoundedCornerFrame=false}, InsetsSource: {mType=ITYPE_BOTTOM_TAPPABLE_ELEMENT, mFrame=[0,2496][1080,2640], mVisible=true, mInsetsRoundedCornerFrame=false}, InsetsSource: {mType=ITYPE_IME, mFrame=[0,0][0,0], mVisibleFrame=[0,1524][1080,2640], mVisible=false, mInsetsRoundedCornerFrame=false} } host=com.example.ble_app/com.example.ble_app.MainActivity from=android.view.ViewRootImpl$ViewRootHandler.handleMessageImpl:6560
I/ViewRootImpl@a08a9fe[MainActivity]: ViewPostIme pointer 0
I/ViewRootImpl@a08a9fe[MainActivity]: ViewPostIme pointer 1
I/System.out: Checked
D/CompatibilityChangeReporter: Compat change id reported: 147798919; UID 10473; state: ENABLED
V/Toast: show: caller = com.example.ble_app.MainActivity$1.onClick:86 
I/ViewRootImpl@a08a9fe[MainActivity]: MSG_WINDOW_FOCUS_CHANGED 0 0
D/InputTransport: Input channel destroyed: 'ClientS', fd=118
I/BluetoothAdapter: onBluetoothStateChange: up=true
D/CompatibilityChangeReporter: Compat change id reported: 78294732; UID 10473; state: ENABLED
I/ViewRootImpl@a08a9fe[MainActivity]: stopped(false) old = false
I/DecorView: notifyKeepScreenOnChanged: keepScreenOn=false
I/MSHandlerLifeCycle: removeMultiSplitHandler: no exist. decor=DecorView@de0b2c8[MainActivity]
D/ViewRootImpl@a08a9fe[MainActivity]: performTraversals params={(0,0)(fillxfill) sim={adjust=pan forwardNavigation} ty=BASE_APPLICATION wanim=0x1030309
      fl=81810100
      pfl=12020040
      bhv=DEFAULT
      fitSides= naviIconColor=0}
D/ViewRootImpl@a08a9fe[MainActivity]: performTraversals mFirst=false windowShouldResize=false viewVisibilityChanged=false mForceNextWindowRelayout=false params={(0,0)(fillxfill) sim={adjust=pan forwardNavigation} ty=BASE_APPLICATION wanim=0x1030309
      fl=81810100
      pfl=12020040
      bhv=DEFAULT
      fitSides= naviIconColor=0}
I/BLASTBufferQueue: update, w= 1080 h= 2640 mName = ViewRootImpl@a08a9fe[MainActivity] mNativeObject= 0xb400007ac470b730 sc.mNativeObject= 0xb400007a54715f10 format= -1 caller= android.view.ViewRootImpl.updateBlastSurfaceIfNeeded:2804 android.view.ViewRootImpl.relayoutWindow:9661 android.view.ViewRootImpl.performTraversals:3785 android.view.ViewRootImpl.doTraversal:3017 android.view.ViewRootImpl$TraversalRunnable.run:10699 android.view.Choreographer$CallbackRecord.run:1301 
I/ViewRootImpl@a08a9fe[MainActivity]: Relayout returned: old=(0,0,1080,2640) new=(0,0,1080,2640) req=(1080,2640)0 dur=5 res=0x0 s={true 0xb400007b5470c110} ch=false seqId=0
I/ViewRootImpl@a08a9fe[MainActivity]: MSG_WINDOW_FOCUS_CHANGED 1 0
D/ViewRootImpl@a08a9fe[MainActivity]: mThreadedRenderer.initializeIfNeeded()#2 mSurface={isValid=true 0xb400007b5470c110}
D/InputMethodManager: startInputInner - Id : 0
I/InputMethodManager: startInputInner - mService.startInputOrWindowGainedFocus
I/ViewRootImpl@a08a9fe[MainActivity]: ViewPostIme pointer 0
I/ViewRootImpl@a08a9fe[MainActivity]: ViewPostIme pointer 1
I/System.out: UnChecked
I/System.out: Disabling the Bluetooth 
I/BluetoothAdapter: disable()
V/Toast: show: caller = com.example.ble_app.MainActivity$1.onClick:99 

Notice the last couple of lines of debug logs:

I/System.out: Disabling the Bluetooth 
I/BluetoothAdapter: disable()
V/Toast: show: caller = com.example.ble_app.MainActivity$1.onClick:99 

But the Bluetooth is still Enabled on my phone.

Logcat logs:

2023-03-21 07:42:50.014 17804-17804 ViewRootIm...nActivity] com.example.ble_app                  I  ViewPostIme pointer 0
2023-03-21 07:42:50.067 17804-17804 ViewRootIm...nActivity] com.example.ble_app                  I  ViewPostIme pointer 1
2023-03-21 07:42:50.071 17804-17804 System.out              com.example.ble_app                  I  Checked
2023-03-21 07:42:50.102 17804-17804 Toast                   com.example.ble_app                  V  show: caller = com.example.ble_app.MainActivity$1.onClick:86 
2023-03-21 07:42:50.138 17804-17804 ViewRootIm...nActivity] com.example.ble_app                  I  MSG_WINDOW_FOCUS_CHANGED 0 0
2023-03-21 07:42:53.416 17804-17859 BluetoothAdapter        com.example.ble_app                  I  onBluetoothStateChange: up=true
2023-03-21 07:42:53.918 17804-17804 ViewRootIm...nActivity] com.example.ble_app                  I  stopped(false) old = false
2023-03-21 07:42:53.920 17804-17804 DecorView               com.example.ble_app                  I  notifyKeepScreenOnChanged: keepScreenOn=false
2023-03-21 07:42:53.924 17804-17804 MSHandlerLifeCycle      com.example.ble_app                  I  removeMultiSplitHandler: no exist. decor=DecorView@200254f[MainActivity]
2023-03-21 07:42:53.933 17804-17804 ViewRootIm...nActivity] com.example.ble_app                  D  performTraversals params={(0,0)(fillxfill) sim={adjust=pan forwardNavigation} ty=BASE_APPLICATION wanim=0x1030309
                                                                                                      fl=81810100
                                                                                                      pfl=12020040
                                                                                                      bhv=DEFAULT
                                                                                                      fitSides= naviIconColor=0}
2023-03-21 07:42:53.935 17804-17804 ViewRootIm...nActivity] com.example.ble_app                  D  performTraversals mFirst=false windowShouldResize=false viewVisibilityChanged=false mForceNextWindowRelayout=false params={(0,0)(fillxfill) sim={adjust=pan forwardNavigation} ty=BASE_APPLICATION wanim=0x1030309
                                                                                                      fl=81810100
                                                                                                      pfl=12020040
                                                                                                      bhv=DEFAULT
                                                                                                      fitSides= naviIconColor=0}
2023-03-21 07:42:53.939 17804-17804 BLASTBufferQueue        com.example.ble_app                  I  update, w= 1080 h= 2640 mName = ViewRootImpl@7a28780[MainActivity] mNativeObject= 0xb400007ac4707bd0 sc.mNativeObject= 0xb400007a547354f0 format= -1 caller= android.view.ViewRootImpl.updateBlastSurfaceIfNeeded:2804 android.view.ViewRootImpl.relayoutWindow:9661 android.view.ViewRootImpl.performTraversals:3785 android.view.ViewRootImpl.doTraversal:3017 android.view.ViewRootImpl$TraversalRunnable.run:10699 android.view.Choreographer$CallbackRecord.run:1301 
2023-03-21 07:42:53.939 17804-17804 ViewRootIm...nActivity] com.example.ble_app                  I  Relayout returned: old=(0,0,1080,2640) new=(0,0,1080,2640) req=(1080,2640)0 dur=4 res=0x0 s={true 0xb400007b54712740} ch=false seqId=0
2023-03-21 07:42:53.947 17804-17804 ViewRootIm...nActivity] com.example.ble_app                  I  MSG_WINDOW_FOCUS_CHANGED 1 0
2023-03-21 07:42:53.948 17804-17804 ViewRootIm...nActivity] com.example.ble_app                  D  mThreadedRenderer.initializeIfNeeded()#2 mSurface={isValid=true 0xb400007b54712740}
2023-03-21 07:42:53.949 17804-17804 InputMethodManager      com.example.ble_app                  D  startInputInner - Id : 0
2023-03-21 07:42:53.949 17804-17804 InputMethodManager      com.example.ble_app                  I  startInputInner - mService.startInputOrWindowGainedFocus


2023-03-21 07:43:17.750 17804-17804 ViewRootIm...nActivity] com.example.ble_app                  I  ViewPostIme pointer 0
2023-03-21 07:43:17.802 17804-17804 ViewRootIm...nActivity] com.example.ble_app                  I  ViewPostIme pointer 1
2023-03-21 07:43:17.806 17804-17804 System.out              com.example.ble_app                  I  UnChecked
2023-03-21 07:43:17.811 17804-17804 System.out              com.example.ble_app                  I  Disabling the Bluetooth 
2023-03-21 07:43:17.811 17804-17804 BluetoothAdapter        com.example.ble_app                  I  disable()
2023-03-21 07:43:17.835 17804-17804 Toast                   com.example.ble_app                  V  show: caller = com.example.ble_app.MainActivity$1.onClick:108 

Hoping to get some clarification regarding this. Thanks in advance!

TheBestPlayer
  • 324
  • 2
  • 13
  • Check out this answer: https://stackoverflow.com/a/28419446/2068732 – matdev Mar 20 '23 at 16:56
  • I have looked at it and it seems that they are using identical methods to what I am using. There are plenty other android and stack overflow posts suggesting that people are having issues with disabling bluetooth, some even mentioned that you are never meant to disable the Bluetooth via the app, some say its possible and you should be able to do it via this disable() method. – TheBestPlayer Mar 21 '23 at 05:38
  • IMHO an app should not have to disable the phone's bluetooth service. Can you explain your use case ? – matdev Mar 24 '23 at 13:38
  • @matdev sorry for late reply. No particular use, just learning and experimenting. – TheBestPlayer Apr 04 '23 at 11:16

1 Answers1

1

Method BluetoothAdapter.disable() is provided only for applications that include a user interface for changing system settings, such as a "power manager" app. This method will not turn off the Bluetooth on your phone without explicit user action to turn off Bluetooth.

Also, this method was deprecated in API level 33. Starting with Build.VERSION_CODES.TIRAMISU, applications are not allowed to enable/disable Bluetooth. For applications targeting Build.VERSION_CODES.TIRAMISU or above, this API will always fail and return false.

You can read more about these restrictions here: https://developer.android.com/reference/android/bluetooth/BluetoothAdapter#disable()

matdev
  • 4,115
  • 6
  • 35
  • 56