Callback from BTLE cannot working properly

Viewed 34

MainActivity.java

public class MainActivity extends AppCompatActivity {
    private Button scan;
    private BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    private BluetoothLeScanner bluetoothLeScanner = bluetoothAdapter.getBluetoothLeScanner();
    private boolean scanning=false;
    private Handler handler = new Handler();
    private static final long SCAN_PERIOD = 10000;

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

        scan = findViewById(R.id.scan);

        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                state();
                Log.d("Logger", "State Check");
                handler.postDelayed(this, 1000);
            }
        }, SCAN_PERIOD);

        scan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(scanning){
                    scan.setText("TURN ON");
                    scanning = false;
                }else{
                    scan.setText("TURN OFF");
                    scanning = true;
                }
            }
        });
    }

    private void state(){
        if(scanning){
            if(bluetoothAdapter!=null){
                if (!bluetoothAdapter.isEnabled()) {
                    Intent eintent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(eintent, 1);
                }else{
                    Log.d("Logger", "state: berhasil akses");
                    bluetoothLeScanner.startScan(leScanCallback);
                }
            }
        }else{
        bluetoothLeScanner.stopScan(leScanCallback);
        }
    }

    private ScanCallback leScanCallback =
            new ScanCallback() {
                @Override
                public void onScanResult(int callbackType, ScanResult result) {
                    super.onScanResult(callbackType, result);
                    Log.d("Logger", "onScanResult: Berhasil Akses");
                    BluetoothDevice newDevice = result.getDevice();
                    String device_address = newDevice.getAddress();
                    Toast.makeText(MainActivity.this,"Device "+device_address+" "+String.valueOf(result.getRssi()),Toast.LENGTH_SHORT).show();
                }
            };
}

This my manifest, i declared the uses-permission. Manifest

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

    <uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
    <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.AndroidBLE">
        <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>

I want to scan BLE using bluetoothLeScanner but my program not working properly. After I debug, it is known that the callback from BTLE cannot be called. Why does this happen and what is the solution? Thank you.

FYI, i am using android 6 API.

1 Answers

According to Android documentation about Bluetooth permissions you must request the location permission to the user (runtime permissions), not only in the manifest

In my project on Android 11 (should be fine also for Android 6) I used this code in the onCreate function of MainActivity class

if (ContextCompat.checkSelfPermission(
        this, Manifest.permission.ACCESS_FINE_LOCATION) !=
        PackageManager.PERMISSION_GRANTED 
) {
    ActivityCompat.requestPermissions(this,new String[] { Manifest.permission.ACCESS_FINE_LOCATION },
            1);
}

And I overrided the onRequestPermissionsResult function

public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                       int[] grantResults) {
    switch (requestCode) {
        case 1:
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0 &&
                    grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                
                Logger.d("MainActivity","Permission approved");
            }  else {
                Logger.d("MainActivity","Error getting permission");
            }
            return;
    }

}

This works for me, I hope would help you

Related