Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Having Issue in Connecting with Android Versions 12 or more #211

Open
haisamk18 opened this issue Jan 20, 2024 · 28 comments
Open

Having Issue in Connecting with Android Versions 12 or more #211

haisamk18 opened this issue Jan 20, 2024 · 28 comments

Comments

@haisamk18
Copy link

This is my error:
Cannot connect, exception occurred: PlatformException(connect_error, Need android.permission.BLUETOOTH_SCAN permission for android.content.AttributionSource@2d842ac7: AdapterService cancelDiscovery, java.lang.SecurityException: Need android.permission.BLUETOOTH_SCAN permission for android.content.AttributionSource@2d842ac7: AdapterService cancelDiscovery

My AndroidManifest.xml code :

<!-- Needed only if your app looks for Bluetooth devices.
     If your app doesn't use Bluetooth scan results to derive physical
     location information, you can
     <a href="#assert-never-for-location">strongly assert that your app
     doesn't derive physical location</a>. -->
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />

<!-- Needed only if your app makes the device discoverable to Bluetooth
     devices. -->
<uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />

<!-- Needed only if your app communicates with already-paired Bluetooth
     devices. -->
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />

<!-- Needed only if your app uses Bluetooth scan results to derive physical location. -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
    android:label="nw"
    android:name="${applicationName}"
    android:icon="@mipmap/ic_launcher">
    <activity
        android:name=".MainActivity"
        android:exported="true"
        android:launchMode="singleTop"
        android:theme="@style/LaunchTheme"
        android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
        android:hardwareAccelerated="true"
        android:windowSoftInputMode="adjustResize">
        <!-- Specifies an Android theme to apply to this Activity as soon as
             the Android process has started. This theme is visible to the user
             while the Flutter UI initializes. After that, this theme continues
             to determine the Window background behind the Flutter UI. -->
        <meta-data
          android:name="io.flutter.embedding.android.NormalTheme"
          android:resource="@style/NormalTheme"
          />
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>
            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>
    </activity>
    <!-- Don't delete the meta-data below.
         This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
    <meta-data
        android:name="flutterEmbedding"
        android:value="2" />
</application>

Help with the issue although I am not using any Scan logic .

@haisamk18
Copy link
Author

The error is consistently coming but in other Android version it is working fine

@fernandomorse
Copy link

I have the same problem. Any solution to fix. Does not work on SDKs above 30.

@zamirszn
Copy link

also have the same issue , I have android 13 , I added the permissions and gave access from the device settings to get it to work

@haisamk18
Copy link
Author

haisamk18 commented Feb 20, 2024 via email

@fernandomorse
Copy link

fernandomorse commented Feb 21, 2024

@haisamk18
I still have the same problem, I'm using:

pubspec.yam

dependencies:
 `   flutter_bluetooth_serial: ^0.4.0`

AndroidManifest.xml
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.BLUETOOTH"/>
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
    <uses-permission android:name="android.permission.BLUETOOTH_SCAN"/>
   <uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE"/>
   <uses-permission android:name="android.permission.BLUETOOTH_CONNECT"/>
   <uses-feature android:name="android.hardware.bluetooth" android:required="false"/>
   <uses-feature android:name="android.hardware.bluetooth_le" android:required="false"/>
     <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
     <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

app\build.gradle
  compileSdkVersion 31

What should I modify to make it work??

@haisamk18
Copy link
Author

haisamk18 commented Feb 21, 2024 via email

@fernandomorse
Copy link

@haisamk18
Correct manually it works, but I believe they should correct it in the next versions, thank you

@zamirszn
Copy link

Unfortunately after adding all the permissions in manifest file it won’t
work.But you can manually give permissions to the app on your phone and
them it will work.

On Wed, 21 Feb 2024 at 10:48 PM, fernandomorse @.***>
wrote:

@haisamk18 https://github.com/haisamk18
I still have the same problem, I'm using:

pubspec.yam

dependencies:
flutter_bluetooth_serial: ^0.4.0

AndroidManifest.xml

app\build.gradle
compileSdkVersion 31

What should I modify to make it work??


Reply to this email directly, view it on GitHub
#211 (comment),
or unsubscribe
https://github.com/notifications/unsubscribe-auth/AWHBWCQFS3T36WESLXNNDMTYUYUAFAVCNFSM6AAAAABCDFHYK2VHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMYTSNJXGM3TAMZRGM
.
You are receiving this because you were mentioned.Message ID:
@.***>

if you ask for permission (nearby device and location) at run time it should work ?

@Lokesh-Enata
Copy link

i was having the same issue don't know whether it has been solved or not but before that i am getting new issue whenever app launches it ask for location permission whenever i click on allow , only for this time or deny button the app crashes and it is only happening for android 13

@zamirszn
Copy link

i was having the same issue don't know whether it has been solved or not but before that i am getting new issue whenever app launches it ask for location permission whenever i click on allow , only for this time or deny button the app crashes and it is only happening for android 13

I notice this if you don't grant nearby devices permission , try asking for nearby devices permission at run time with permission handler

@Lokesh-Enata
Copy link

i was having the same issue don't know whether it has been solved or not but before that i am getting new issue whenever app launches it ask for location permission whenever i click on allow , only for this time or deny button the app crashes and it is only happening for android 13

I notice this if you don't grant nearby devices permission , try asking for nearby devices permission at run time with permission handler

@Lokesh-Enata
Copy link

i think the flutter bluetooth serial package does not supports android 13

@haisamk18
Copy link
Author

haisamk18 commented Feb 23, 2024 via email

@Lokesh-Enata
Copy link

Lokesh-Enata commented Feb 23, 2024

yes may be you are right but my app first ask location even if i allow it crashes i m not getting why
even i have turn on nearby share on i can't even move forward

@Christyansoft
Copy link

@Lokesh-Enata same problem here, did you find a solution ?

@Lokesh-Enata
Copy link

@Lokesh-Enata same problem here, did you find a solution ?

yess , i used flutter bluetooth serial ble package that solved my problem.

@zamirszn
Copy link

@Lokesh-Enata same problem here, did you find a solution ?

yess , i used flutter bluetooth serial ble package that solved my problem.

hello , can you help with a link to the package please

@Lokesh-Enata
Copy link

@Lokesh-Enata same problem here, did you find a solution ?

yess , i used flutter bluetooth serial ble package that solved my problem.

hello , can you help with a link to the package please

sure, 'https://pub.dev/packages/flutter_bluetooth_serial_ble' this is the link for the package.

@zamirszn
Copy link

@Lokesh-Enata same problem here, did you find a solution ?

yess , i used flutter bluetooth serial ble package that solved my problem.

hello , can you help with a link to the package please

sure, 'https://pub.dev/packages/flutter_bluetooth_serial_ble' this is the link for the package.

thanks alot

@Christyansoft
Copy link

Christyansoft commented Feb 29, 2024

Unfortunately the flutter flutter_bluettoth_serial_ble has the same problem. When request location at the first time in android 12 or later, crashs the app. there are another similar packages that do the same, but the owners sounds like do not approve the pr's 🙃

@zamirszn
Copy link

Unfortunately the flutter flutter_bluettoth_serial_ble has the same problem. When request location at the first time in android 12 or later, crashs the app. there are another similar packages that do the same, but the owners sounds like do not approve the pr's 🙃

I'm running a build and looking for a fix , I'll let you know how it goes

@zamirszn
Copy link

Unfortunately the flutter flutter_bluettoth_serial_ble has the same problem. When request location at the first time in android 12 or later, crashs the app. there are another similar packages that do the same, but the owners sounds like do not approve the pr's 🙃

ive been able to fix this

you can add

 <uses-permission android:name="android.permission.INTERNET"/>
 <uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.BLUETOOTH_PRIVILEGED" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

in your manifest not all of them are required?

then before anything else request for the bluetooth Connect permission

Permission.bluetoothConnect.request()

you can use the permission_handler package then initialize the bluetooth method , below is the full code

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_bluetooth_serial_ble/flutter_bluetooth_serial_ble.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:scoped_model/scoped_model.dart';

import './BackgroundCollectedPage.dart';
import './BackgroundCollectingTask.dart';
import './ChatPage.dart';
import './DiscoveryPage.dart';
import './SelectBondedDevicePage.dart';

// import './helpers/LineChart.dart';

class MainPage extends StatefulWidget {
  @override
  _MainPage createState() => new _MainPage();
}

class _MainPage extends State<MainPage> {
  BluetoothState _bluetoothState = BluetoothState.UNKNOWN;

  String _address = "...";
  String _name = "...";

  Timer? _discoverableTimeoutTimer;
  int _discoverableTimeoutSecondsLeft = 0;

  BackgroundCollectingTask? _collectingTask;

  bool _autoAcceptPairingRequests = false;

  @override
  void initState() {
    // Get current state
    super.initState();
  }

  void initBT() {
    FlutterBluetoothSerial.instance.state.then((state) {
      setState(() {
        _bluetoothState = state;
      });
    });

    Future.doWhile(() async {
      // Wait if adapter not enabled
      if ((await FlutterBluetoothSerial.instance.isEnabled) ?? false) {
        return false;
      }
      await Future.delayed(Duration(milliseconds: 0xDD));
      return true;
    }).then((_) {
      // Update the address field
      FlutterBluetoothSerial.instance.address.then((address) {
        setState(() {
          _address = address!;
        });
      });
    });

    FlutterBluetoothSerial.instance.name.then((name) {
      setState(() {
        _name = name!;
      });
    });

    // Listen for futher state changes
    FlutterBluetoothSerial.instance
        .onStateChanged()
        .listen((BluetoothState state) {
      setState(() {
        _bluetoothState = state;

        // Discoverable mode is disabled when Bluetooth gets disabled
        _discoverableTimeoutTimer = null;
        _discoverableTimeoutSecondsLeft = 0;
      });
    });
  }

  @override
  void dispose() {
    FlutterBluetoothSerial.instance.setPairingRequestHandler(null);
    _collectingTask?.dispose();
    _discoverableTimeoutTimer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Flutter Bluetooth Serial'),
      ),
      body: FutureBuilder<PermissionStatus>(
          future: Permission.bluetoothConnect.request(),
          builder: (context, snapshot) {
            if (snapshot.hasData && snapshot.data == PermissionStatus.granted) {
              initBT();

              return Container(
                child: ListView(
                  children: <Widget>[
                    Divider(),
                    ListTile(title: const Text('General')),
                    SwitchListTile(
                      title: const Text('Enable Bluetooth'),
                      value: _bluetoothState.isEnabled,
                      onChanged: (bool value) {
                        // Do the request and update with the true value then
                        future() async {
                          // async lambda seems to not working
                          if (value)
                            await FlutterBluetoothSerial.instance
                                .requestEnable();
                          else
                            await FlutterBluetoothSerial.instance
                                .requestDisable();
                        }

                        future().then((_) {
                          setState(() {});
                        });
                      },
                    ),
                    ListTile(
                      title: const Text('Bluetooth status'),
                      subtitle: Text(_bluetoothState.toString()),
                      trailing: ElevatedButton(
                        child: const Text('Settings'),
                        onPressed: () {
                          FlutterBluetoothSerial.instance.openSettings();
                        },
                      ),
                    ),
                    ListTile(
                      title: const Text('Local adapter address'),
                      subtitle: Text(_address),
                    ),
                    ListTile(
                      title: const Text('Local adapter name'),
                      subtitle: Text(_name),
                      onLongPress: null,
                    ),
                    ListTile(
                      title: _discoverableTimeoutSecondsLeft == 0
                          ? const Text("Discoverable")
                          : Text(
                              "Discoverable for ${_discoverableTimeoutSecondsLeft}s"),
                      subtitle: const Text("PsychoX-Luna"),
                      trailing: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Checkbox(
                            value: _discoverableTimeoutSecondsLeft != 0,
                            onChanged: null,
                          ),
                          IconButton(
                            icon: const Icon(Icons.edit),
                            onPressed: null,
                          ),
                          IconButton(
                            icon: const Icon(Icons.refresh),
                            onPressed: () async {
                              print('Discoverable requested');
                              final int timeout = (await FlutterBluetoothSerial
                                  .instance
                                  .requestDiscoverable(60))!;
                              if (timeout < 0) {
                                print('Discoverable mode denied');
                              } else {
                                print(
                                    'Discoverable mode acquired for $timeout seconds');
                              }
                              setState(() {
                                _discoverableTimeoutTimer?.cancel();
                                _discoverableTimeoutSecondsLeft = timeout;
                                _discoverableTimeoutTimer = Timer.periodic(
                                    Duration(seconds: 1), (Timer timer) {
                                  setState(() {
                                    if (_discoverableTimeoutSecondsLeft < 0) {
                                      FlutterBluetoothSerial
                                          .instance.isDiscoverable
                                          .then((isDiscoverable) {
                                        if (isDiscoverable ?? false) {
                                          print(
                                              "Discoverable after timeout... might be infinity timeout :F");
                                          _discoverableTimeoutSecondsLeft += 1;
                                        }
                                      });
                                      timer.cancel();
                                      _discoverableTimeoutSecondsLeft = 0;
                                    } else {
                                      _discoverableTimeoutSecondsLeft -= 1;
                                    }
                                  });
                                });
                              });
                            },
                          )
                        ],
                      ),
                    ),
                    Divider(),
                    ListTile(
                        title: const Text('Devices discovery and connection')),
                    SwitchListTile(
                      title: const Text('Auto-try specific pin when pairing'),
                      subtitle: const Text('Pin 1234'),
                      value: _autoAcceptPairingRequests,
                      onChanged: (bool value) {
                        setState(() {
                          _autoAcceptPairingRequests = value;
                        });
                        if (value) {
                          FlutterBluetoothSerial.instance
                              .setPairingRequestHandler(
                                  (BluetoothPairingRequest request) {
                            print("Trying to auto-pair with Pin 1234");
                            if (request.pairingVariant == PairingVariant.Pin) {
                              return Future.value("1234");
                            }
                            return Future.value(null);
                          });
                        } else {
                          FlutterBluetoothSerial.instance
                              .setPairingRequestHandler(null);
                        }
                      },
                    ),
                    ListTile(
                      title: ElevatedButton(
                          child: const Text('Explore discovered devices'),
                          onPressed: () async {
                            final BluetoothDevice? selectedDevice =
                                await Navigator.of(context).push(
                              MaterialPageRoute(
                                builder: (context) {
                                  return DiscoveryPage();
                                },
                              ),
                            );

                            if (selectedDevice != null) {
                              print('Discovery -> selected ' +
                                  selectedDevice.address);
                            } else {
                              print('Discovery -> no device selected');
                            }
                          }),
                    ),
                    ListTile(
                      title: ElevatedButton(
                        child: const Text('Connect to paired device to chat'),
                        onPressed: () async {
                          final BluetoothDevice? selectedDevice =
                              await Navigator.of(context).push(
                            MaterialPageRoute(
                              builder: (context) {
                                return SelectBondedDevicePage(
                                    checkAvailability: false);
                              },
                            ),
                          );

                          if (selectedDevice != null) {
                            print('Connect -> selected ' +
                                selectedDevice.address);
                            _startChat(context, selectedDevice);
                          } else {
                            print('Connect -> no device selected');
                          }
                        },
                      ),
                    ),
                    Divider(),
                    ListTile(title: const Text('Multiple connections example')),
                    ListTile(
                      title: ElevatedButton(
                        child: ((_collectingTask?.inProgress ?? false)
                            ? const Text(
                                'Disconnect and stop background collecting')
                            : const Text(
                                'Connect to start background collecting')),
                        onPressed: () async {
                          if (_collectingTask?.inProgress ?? false) {
                            await _collectingTask!.cancel();
                            setState(() {
                              /* Update for `_collectingTask.inProgress` */
                            });
                          } else {
                            final BluetoothDevice? selectedDevice =
                                await Navigator.of(context).push(
                              MaterialPageRoute(
                                builder: (context) {
                                  return SelectBondedDevicePage(
                                      checkAvailability: false);
                                },
                              ),
                            );

                            if (selectedDevice != null) {
                              await _startBackgroundTask(
                                  context, selectedDevice);
                              setState(() {
                                /* Update for `_collectingTask.inProgress` */
                              });
                            }
                          }
                        },
                      ),
                    ),
                    ListTile(
                      title: ElevatedButton(
                        child: const Text('View background collected data'),
                        onPressed: (_collectingTask != null)
                            ? () {
                                Navigator.of(context).push(
                                  MaterialPageRoute(
                                    builder: (context) {
                                      return ScopedModel<
                                          BackgroundCollectingTask>(
                                        model: _collectingTask!,
                                        child: BackgroundCollectedPage(),
                                      );
                                    },
                                  ),
                                );
                              }
                            : null,
                      ),
                    ),
                  ],
                ),
              );
            }
            if (snapshot.data == PermissionStatus.permanentlyDenied) {
              openAppSettings();
            }
            return Center(
              child: ElevatedButton(
                child: Text("Grant permission"),
                onPressed: () {
                  setState(() {});
                },
              ),
            );
          }),
    );
  }

  void _startChat(BuildContext context, BluetoothDevice server) {
    Navigator.of(context).push(
      MaterialPageRoute(
        builder: (context) {
          return ChatPage(server: server);
        },
      ),
    );
  }

  Future<void> _startBackgroundTask(
    BuildContext context,
    BluetoothDevice server,
  ) async {
    try {
      _collectingTask = await BackgroundCollectingTask.connect(server);
      await _collectingTask!.start();
    } catch (ex) {
      _collectingTask?.cancel();
      showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: const Text('Error occured while connecting'),
            content: Text("${ex.toString()}"),
            actions: <Widget>[
              new TextButton(
                child: new Text("Close"),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              ),
            ],
          );
        },
      );
    }
  }
}


and lastly i had to use compileSdkVersion 33

@Lokesh-Enata
Copy link

Lokesh-Enata commented Mar 1, 2024

Unfortunately the flutter flutter_bluettoth_serial_ble has the same problem. When request location at the first time in android 12 or later, crashs the app. there are another similar packages that do the same, but the owners sounds like do not approve the pr's 🙃

No what i have done is if we go and directly run the repo app of this project it will work fine on android 12 but will crash in android 13 so i imported discovery page, bluetooth list and connnection page code only from the repo project and i used scoped model and flutter bluetooth serial ble package and that fixed my issue i can connect , send and receive data

@Christyansoft
Copy link

Hi guys, I add all permissions in manifest, updated the permission_handler pacakge and compileSdkVersion is 33.

I just do Permission.bluetoothConnect.request(); with permission_handler, and automatically, request bluetooth and location. Even if is granted, the app crash at the first time, and shows the error:

E/AndroidRuntime(11660): FATAL EXCEPTION: main
E/AndroidRuntime(11660): java.lang.RuntimeException: Failure delivering result ResultInfo{who=@android:requestPermissions:, request=1451, result=-1, data=Intent { act=android.content.pm.action.REQUEST_PERMISSIONS (has extras) }} to activity {app.MainActivity}: java.lang.NullPointerException: Attempt to invoke interface method 'void io.flutter.plugin.common.MethodChannel$Result.success(java.lang.Object)' on a null object reference
E/AndroidRuntime(11660): at android.app.ActivityThread.deliverResults(ActivityThread.java:5375)
E/AndroidRuntime(11660): at android.app.ActivityThread.handleSendResult(ActivityThread.java:5414)
E/AndroidRuntime(11660): at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:54)
E/AndroidRuntime(11660): at android.app.servertransaction.ActivityTransactionItem.execute(ActivityTransactionItem.java:45)
E/AndroidRuntime(11660): at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
E/AndroidRuntime(11660): at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
E/AndroidRuntime(11660): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2281)
E/AndroidRuntime(11660): at android.os.Handler.dispatchMessage(Handler.java:106)
E/AndroidRuntime(11660): at android.os.Looper.loopOnce(Looper.java:223)
E/AndroidRuntime(11660): at android.os.Looper.loop(Looper.java:317)
E/AndroidRuntime(11660): at android.app.ActivityThread.main(ActivityThread.java:7942)
E/AndroidRuntime(11660): at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime(11660): at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:568)
E/AndroidRuntime(11660): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1045)
E/AndroidRuntime(11660): Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'void io.flutter.plugin.common.MethodChannel$Result.success(java.lang.Object)' on a null object reference
E/AndroidRuntime(11660): at id.kakzaki.blue_thermal_printer.BlueThermalPrinterPlugin.getBondedDevices(BlueThermalPrinterPlugin.java:462)
E/AndroidRuntime(11660): at id.kakzaki.blue_thermal_printer.BlueThermalPrinterPlugin.onRequestPermissionsResult(BlueThermalPrinterPlugin.java:413)
E/AndroidRuntime(11660): at io.flutter.embedding.engine.FlutterEngineConnectionRegistry$FlutterEngineActivityPluginBinding.onRequestPermissionsResult(FlutterEngineConnectionRegistry.java:785)
E/AndroidRuntime(11660): at io.flutter.embedding.engine.FlutterEngineConnectionRegistry.onRequestPermissionsResult(FlutterEngineConnectionRegistry.java:413)
E/AndroidRuntime(11660): at io.flutter.embedding.android.FlutterActivityAndFragmentDelegate.onRequestPermissionsResult(FlutterActivityAndFragmentDelegate.java:801)
E/AndroidRuntime(11660): at io.flutter.embedding.android.FlutterActivity.onRequestPermissionsResult(FlutterActivity.java:908)
E/AndroidRuntime(11660): at android.app.Activity.dispatchRequestPermissionsResult(Activity.java:8593)
E/AndroidRuntime(11660): at android.app.Activity.dispatchActivityResult(Activity.java:8450)
E/AndroidRuntime(11660): at android.app.ActivityThread.deliverResults(ActivityThread.java:5368)
E/AndroidRuntime(11660):

@zamirszn
Copy link

zamirszn commented Mar 1, 2024

Hi guys, I add all permissions in manifest, updated the permission_handler pacakge and compileSdkVersion is 33.

I just do Permission.bluetoothConnect.request(); with permission_handler, and automatically, request bluetooth and location. Even if is granted, the app crash at the first time, and shows the error:

E/AndroidRuntime(11660): FATAL EXCEPTION: main
E/AndroidRuntime(11660): java.lang.RuntimeException: Failure delivering result ResultInfo{who=@android:requestPermissions:, request=1451, result=-1, data=Intent { act=android.content.pm.action.REQUEST_PERMISSIONS (has extras) }} to activity {app.MainActivity}: java.lang.NullPointerException: Attempt to invoke interface method 'void io.flutter.plugin.common.MethodChannel$Result.success(java.lang.Object)' on a null object reference
E/AndroidRuntime(11660): at android.app.ActivityThread.deliverResults(ActivityThread.java:5375)
E/AndroidRuntime(11660): at android.app.ActivityThread.handleSendResult(ActivityThread.java:5414)
E/AndroidRuntime(11660): at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:54)
E/AndroidRuntime(11660): at android.app.servertransaction.ActivityTransactionItem.execute(ActivityTransactionItem.java:45)
E/AndroidRuntime(11660): at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
E/AndroidRuntime(11660): at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
E/AndroidRuntime(11660): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2281)
E/AndroidRuntime(11660): at android.os.Handler.dispatchMessage(Handler.java:106)
E/AndroidRuntime(11660): at android.os.Looper.loopOnce(Looper.java:223)
E/AndroidRuntime(11660): at android.os.Looper.loop(Looper.java:317)
E/AndroidRuntime(11660): at android.app.ActivityThread.main(ActivityThread.java:7942)
E/AndroidRuntime(11660): at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime(11660): at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:568)
E/AndroidRuntime(11660): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1045)
E/AndroidRuntime(11660): Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'void io.flutter.plugin.common.MethodChannel$Result.success(java.lang.Object)' on a null object reference
E/AndroidRuntime(11660): at id.kakzaki.blue_thermal_printer.BlueThermalPrinterPlugin.getBondedDevices(BlueThermalPrinterPlugin.java:462)
E/AndroidRuntime(11660): at id.kakzaki.blue_thermal_printer.BlueThermalPrinterPlugin.onRequestPermissionsResult(BlueThermalPrinterPlugin.java:413)
E/AndroidRuntime(11660): at io.flutter.embedding.engine.FlutterEngineConnectionRegistry$FlutterEngineActivityPluginBinding.onRequestPermissionsResult(FlutterEngineConnectionRegistry.java:785)
E/AndroidRuntime(11660): at io.flutter.embedding.engine.FlutterEngineConnectionRegistry.onRequestPermissionsResult(FlutterEngineConnectionRegistry.java:413)
E/AndroidRuntime(11660): at io.flutter.embedding.android.FlutterActivityAndFragmentDelegate.onRequestPermissionsResult(FlutterActivityAndFragmentDelegate.java:801)
E/AndroidRuntime(11660): at io.flutter.embedding.android.FlutterActivity.onRequestPermissionsResult(FlutterActivity.java:908)
E/AndroidRuntime(11660): at android.app.Activity.dispatchRequestPermissionsResult(Activity.java:8593)
E/AndroidRuntime(11660): at android.app.Activity.dispatchActivityResult(Activity.java:8450)
E/AndroidRuntime(11660): at android.app.ActivityThread.deliverResults(ActivityThread.java:5368)
E/AndroidRuntime(11660):

can you share your code , so I can test with my device

@Christyansoft
Copy link

Sorry, i can't, but I just trying requestPermission using:

flutter_bluetooth_serial: ^0.4.0
permission_handler: ^11.3.0
Android 12

Manifest:
<uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> <uses-permission android:name="android.permission.BLUETOOTH_SCAN" /> <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" /> <uses-permission android:name="android.permission.BLUETOOTH_PRIVILEGED" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.FOREGROUND_SERVICE" /> <uses-permission android:name="android.permission.WAKE_LOCK" /> <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" /> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> <uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" /> <uses-permission android:name="android.permission.READ_MEDIA_IMAGES" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" android:maxSdkVersion="33" />

like:

final permissionResult = await Permission.bluetoothConnect.request();
Just do it at the first time and app will crash

@zamirszn
Copy link

zamirszn commented Mar 1, 2024

Sorry, i can't, but I just trying requestPermission using:

flutter_bluetooth_serial: ^0.4.0
permission_handler: ^11.3.0
Android 12

Manifest:
<uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> <uses-permission android:name="android.permission.BLUETOOTH_SCAN" /> <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" /> <uses-permission android:name="android.permission.BLUETOOTH_PRIVILEGED" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.FOREGROUND_SERVICE" /> <uses-permission android:name="android.permission.WAKE_LOCK" /> <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" /> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> <uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" /> <uses-permission android:name="android.permission.READ_MEDIA_IMAGES" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" android:maxSdkVersion="33" />

like:

final permissionResult = await Permission.bluetoothConnect.request();
Just do it at the first time and app will crash

ok I'll try it

@Christyansoft
Copy link

The same happens with flutter_bluetooth_serial_ble

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants