Flutter ble - write characteristic error
I'm not being able to write on ble pheriperal device, using flutter_blue library, it throws this exception:
Unhandled Exception: PlatformException(write_characteristic_error, service (0000ff06-0000-1000-8000-00805f9b34fb) could not be located on the device, null, null)
E/flutter (29808): #0 StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:607:7)
E/flutter (29808): #1 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:167:18)
E/flutter (29808): <asynchronous suspension>
E/flutter (29808): #2 BluetoothCharacteristic.write (package:flutter_blue/src/bluetooth_characteristic.dart:120:18)
E/flutter (29808): <asynchronous suspension>
E/flutter (29808): #3 DeviceScreen._buildServiceTiles.<anonymous closure>.<anonymous closure>.<anonymous closure> (package:untitled/main.dart:176:23)
or another error saying : Write is not permited.
I'm using example code provided by flutter blue library, here is the code that im trying to write after device is connected:
onWritePressed: () async {
await c.write(_getRandomBytes(), withoutResponse: true);
await c.read();
},
onNotificationPressed: () async {
await c.setNotifyValue(!c.isNotifying);
if (c.properties.read) {
await c.read();
}
List<int> _getRandomBytes(){
String command = "55 AA 00 01 50 3C 00";
return command.codeUnits;
}
The hardware device is working fine in Kotlin, data is sent and received.
Related
I try to run a url using url lancher package
https://pub.dev/packages/url_launcher
and i got this error , i use a package to display my app over apps , using that package https://pub.dev/packages/flutter_overlay_window , and i added a button inside the overlay and when i press it it supposed to send a message to whatsapp using url lancher package , but the problem is that when your app is over apps you will get that error :
E/flutter (24166): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: PlatformException(NO_ACTIVITY, Launching a URL requires a foreground activity., null, null)
E/flutter (24166): #0 StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:607:7)
E/flutter (24166): #1 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:177:18)E/flutter (24166): <asynchronous suspension>
E/flutter (24166): #2 launchUrlString (package:url_launcher/src/url_launcher_string.dart:39:10)
E/flutter (24166): <asynchronous suspension>
E/flutter (24166): #3 launchUrl (package:url_launcher/src/url_launcher_uri.dart:57:10)
Constantly getting this error since i override the ErrorWidget.builder in the main function. I only see the exception i navigate to a specific widget(Not initially. I be on the page for few minutes, this starts getting printed automatically in console gradually & keeps printing. Once this error appears on console, i see this error every time i tap on something. package:flutter/src/widgets/navigator.dart': Failed assertion: line 1748 pos 12: '!_debugLocked': is not true. ) . The problem i face is , i don't know where to lookup for the reason..came up all in sudden today & i have no clue to debug. Has anybody else seen this error before ??
E/flutter (25849): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: NoSuchMethodError: The method 'round' was called on null.
E/flutter (25849): Receiver: null
E/flutter (25849): Tried calling: round()
E/flutter (25849): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:53:5)
E/flutter (25849): #1 PageController.nextPage (package:flutter/src/widgets/page_view.dart:227:31)
E/flutter (25849): #2 _CarouselSliderState.getTimer.<anonymous closure> (package:carousel_slider/carousel_slider.dart:172:14)
E/flutter (25849): #3 _rootRunUnary (dart:async/zone.dart:1192:38)
E/flutter (25849): #4 _CustomZone.runUnary (dart:async/zone.dart:1085:19)
E/flutter (25849): #5 _CustomZone.runUnaryGuarded (dart:async/zone.dart:987:7)
E/flutter (25849): #6 _CustomZone.bindUnaryCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1024:26)
E/flutter (25849): #7 _rootRunUnary (dart:async/zone.dart:1196:13)
E/flutter (25849): #8 _CustomZone.runUnary (dart:async/zone.dart:1085:19)
E/flutter (25849): #9 _CustomZone.bindUnaryCallback.<anonymous closure> (dart:async/zone.dart:1008:26)
E/flutter (25849): #10 _Timer._runTimers (dart:isolate-patch/timer_impl.dart:398:19)
E/flutter (25849): #11 _Timer._handleMessage (dart:isolate-patch/timer_impl.dart:429:5)
E/flutter (25849): #12 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:168:12)
E/flutter (25849):
if you use carousel_pro. it's from the plugin src.
try update
if ((_controller.page!=null) && (_controller.page.round() == widget.images.length - 1)) {
I already create pull request to the source. hope it will be updated.
cheers
After setting up my project with a local Firebase functions emulator as my backend, and calling my Firebase onCall function from my Android emulator, I get this very non-informative error message PlatformException(functionsError, Cloud function failed with exception., {code: INTERNAL, details: null, message: INTERNAL}). Full error message below:
E/flutter (20862): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: PlatformException(functionsError, Cloud function failed with exception., {code: INTERNAL, details: null, message: INTERNAL})
E/flutter (21445): #0 StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:569:7)
E/flutter (21445): #1 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:156:18)
E/flutter (21445): <asynchronous suspension>
E/flutter (21445): #2 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:329:12)
E/flutter (21445): #3 MethodChannelCloudFunctions.callCloudFunction (package:cloud_functions_platform_interface/src/method_channel_cloud_functions.dart:43:15)
E/flutter (21445): #4 HttpsCallable.call (package:cloud_functions/src/https_callable.dart:33:12)
E/flutter (21445): #5 ApiService.loadUserLessonsByLessonIds (package:kim/services/api.dart:28:21)
E/flutter (21445): #6 MapScreen.build.<anonymous closure> (package:kim/screens/map.dart:170:34)
E/flutter (21445): #7 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:779:19)
E/flutter (21445): #8 _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:862:36)
E/flutter (21445): #9 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:182:24)
E/flutter (21445): #10 TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:504:11)
E/flutter (21445): #11 BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:282:5)
E/flutter (21445): #12 BaseTapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:217:7)
E/flutter (21445): #13 PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:475:9)
E/flutter (21445): #14 PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:76:12)
E/flutter (21445): #15 PointerRouter._dispatchEventToRoutes.<anonymous closure> (package:flutter/src/gestures/pointer_router.dart:122:9)
E/flutter (21445): #16 _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:379:8)
E/flutter (21445): #17 PointerRouter._dispatchEventToRoutes (package:flutter/src/gestures/pointer_router.dart:120:18)
E/flutter (21445): #18 PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:106:7)
E/flutter (21445): #19 GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:218:19)
E/flutter (21445): #20 GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:198:22)
E/flutter (21445): #21 GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:156:7)
E/flutter (21445): #22 GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:102:7)
E/flutter (21445): #23 GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:86:7)
E/flutter (21445): #24 _rootRunUnary (dart:async/zone.dart:1196:13)
E/flutter (21445): #25 _CustomZone.runUnary (dart:async/zone.dart:1085:19)
E/flutter (21445): #26 _CustomZone.runUnaryGuarded (dart:async/zone.dart:987:7)
E/flutter (21445): #27 _invoke1 (dart:ui/hooks.dart:275:10)
E/flutter (21445): #28 _dispatchPointerDataPacket (dart:ui/hooks.dart:184:5)
E/flutter (21445):
The server code index.ts:
import * as functions from 'firebase-functions'
interface LoadUserLessonsData {
lessonIds: string[]
}
export const loadUserLessons = functions.https.onCall((data: LoadUserLessonsData, context) => {
const uid = context.auth?.uid
const ids = data.lessonIds
console.log(uid, ids)
})
The server console window after running firebase emulators:start --only functions:
...
+ functions[loadUserLessons]: http function initialized (http://localhost:5001/project-name/us-central1/loadUserLessons).
...
┌───────────┬────────────────┬─────────────────────────────────┐
│ Emulator │ Host:Port │ View in Emulator UI │
├───────────┼────────────────┼─────────────────────────────────┤
│ Functions │ localhost:5001 │ http://localhost:4000/functions │
└───────────┴────────────────┴─────────────────────────────────┘
The client app code api.dart:
import 'dart:io';
import 'package:cloud_functions/cloud_functions.dart';
import 'package:myapp/services/config.dart';
class ApiService {
static final ApiService _apiService = ApiService._internal();
static final _functions = CloudFunctions.instance;
ApiService._internal();
factory ApiService() {
init();
return _apiService;
}
static void init() {
// 10.0.2.2 is the special IP address to connect to the 'localhost' of the host computer from an Android emulator.
final origin = Platform.isAndroid ? 'http://10.0.2.2:5001' : 'http://localhost:5001';
_functions.useFunctionsEmulator(origin: origin);
}
static Future<dynamic> loadUserLessons(List<String> lessonIds) {
final HttpsCallable callable = _functions.getHttpsCallable(
functionName: 'loadUserLessons',
);
return callable.call({
'lessonIds': lessonIds,
});
}
}
What can I do to correctly setup my Flutter app to connect to my local emulator?
It should be noted that the error message is the same regardless if the emulator is running or not. The emulator doesn't register any events in the console logs either. However, when the emulator is running, sending an custom request (e.g. through an Android app like "REST Api Client") to the function endpoint does make the emulator react.
This means that the problem is solely in the Flutter code (mine or cloud_functions Flutter package). At least, that's my conclusion so far.
Luckily I had set up Crashlytics that had been given more detailed error messages, one of which was:
CLEARTEXT communication to 10.0.2.2 not permitted by network security policy
which pointed me to this Stackoverflow question and the comment made by Ashish John:
OkHttp: <-- HTTP FAILED: java.net.UnknownServiceException: CLEARTEXT communication to 10.0.2.2 not permitted by network security policy
You can you 'android:usesCleartextTraffic="true"' in 'Application' tag in manifest file. This problem occurs if your API/Link doe not support https & you are using 'Android P' or above.
Reading up more on android:usesCleartextTraffic https://developer.android.com/guide/topics/manifest/application-element
Indicates whether the app intends to use cleartext network traffic, such as cleartext HTTP. The default value for apps that target API level 27 or lower is "true". Apps that target API level 28 or higher default to "false".
In other words, if your Android emulator is running Android API level 28 or higher you need to add android:usesCleartextTraffic="true" to the <application> tag in your app's AndroidManifest.xml
Now we need to permit the traffic between Android emulator and the Firebase functions emulator, which Ahmed Ghrib solved.
OkHttp: <-- HTTP FAILED: java.net.UnknownServiceException: CLEARTEXT communication to 10.0.2.2 not permitted by network security policy
Create a file network_security_config.xml and place it in [PROJECT]/android/app/src/main/res/xml with the following code:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
<domain>10.0.2.2</domain>
</domain-config>
</network-security-config>
This is a modified version made to Ahmed Ghrib's answer, to limit clear text traffic to only be used between the Android emulator and the Firebase functions emulator.
I've searched the whole internet, tried every possible solution, still I'm not being able to sign in using GoogleSignIn from my flutter app.
Things I've tried :
1. Added SHA-1 Certificate
2. Added SHA-256 Certificate
3. Filled O-Auth Screen
4. Enabled GoogleSignIn in firebase
5. Added support email
Testing currently only in debug mode. As the app is in its initial stages right now I don't want to build a release version yet. Using debug SHA-1 and SHA-256 fingerprints.
Future<FirebaseUser> _signIn(BuildContext context) async {
final GoogleSignInAccount googleUser = await _googleSignIn.signIn();
final GoogleSignInAuthentication googleAuth =
await googleUser.authentication;
final AuthCredential credential = GoogleAuthProvider.getCredential(
accessToken: googleAuth.accessToken, idToken: googleAuth.idToken);
AuthResult userDetails =
await _firebaseAuth.signInWithCredential(credential);
ProviderDetails providerInfo =
ProviderDetails(userDetails.user.providerId);
List<ProviderDetails> providerData = List<ProviderDetails>();
providerData.add(providerInfo);
UserDetails details = UserDetails(
providerDetails: userDetails.user.providerId,
userEmail: userDetails.user.email,
userName: userDetails.user.displayName,
photoUrl: userDetails.user.photoUrl,
providerData: providerData);
return userDetails.user;
}
Error I get
[ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception:
PlatformException(sign_in_failed,
com.google.android.gms.common.api.ApiException: 10: , null)
E/flutter (12322): #0 StandardMethodCodec.decodeEnvelope
package:flutter/…/services/message_codecs.dart:564
E/flutter (12322): #1 MethodChannel.invokeMethod
package:flutter/…/services/platform_channel.dart:316
E/flutter (12322): <asynchronous suspension>
E/flutter (12322): #2 MethodChannel.invokeMapMethod
package:flutter/…/services/platform_channel.dart:344
E/flutter (12322): <asynchronous suspension>
E/flutter (12322): #3 GoogleSignIn._callMethod
package:google_sign_in/google_sign_in.dart:218
E/flutter (12322): <asynchronous suspension>
E/flutter (12322): #4 GoogleSignIn._addMethodCall.<anonymous closure>
package:google_sign_in/google_sign_in.dart:27
E/flutter (12322): #5 _rootRun (dart:async/zone.dart:1120:38)
E/flutter (12322): #6 _CustomZone.run (dart:async/zone.dart:1021:19)
E/flutter (12322): #7 _FutureListener.handleWhenComplete
(dart:async/future_impl.dart:150:18)
E/flutter (12322): #8
Future._propagateToListeners.handleWhenCompleteCallback
(dart:async/future_impl.dart:609:39)
E/flutter (12322): #9 Future._propagateToListeners
(dart:async/future_impl.dart:665:37)
E/flutter (12322): #10 Future._addListener.<anonymous closure>
(dart:async/future_impl.dart:348:9)
E/flutter (12322): #11 _rootRun (dart:async/zone.dart:1124:13)
E/flutter (12322): #12 _CustomZone.run (dart:async/zone.dart:1021:19)
E/flutter (12322): #13 _CustomZone.runGuarded
(dart:async/zone.dart:923:7)
E/flutter (12322): #14 _CustomZone.bindCallbackGuarded.<anonymous
closure> (dart:async/zone.dart:963:23)
E/flutter (12322): #15 _microtaskLoop
(dart:async/schedule_microtask.dart:41:21)
E/flutter (12322): #16 _startMicrotaskLoop
(dart:async/schedule_microtask.dart:50:5)
E/flutter (12322):
I know this question was posted quite some time ago but in case anybody else had issues, in addition to all of the above steps, I also enabled Google People API. Make sure that you are on the right email and project.
https://console.developers.google.com/apis/library/people.googleapis.com?q=people&id=5877a7af-1d13-4098-a53e-b5e2d7a87a4f&project=phamton-test
Did you rebuild the project after adding the dependencies?
Sometimes you need to rebuild your project whenever you add any platform specific plugin before it can be used effectively
So as regards to this error, if you find yourself facing it at any point.
There are 2 things that could possibly be wrong
Your app is not on the playstore and you're testing locally with a signed app.
You should probably go and add more SHA keys, if you have only SHA-1 go ahead and put SHA-256. Also be weary of your test environment as it could also mean that your apk mode(Testing or Production) is not correlating.
I want to have a dart background service running forever (isolates) which will communicate with a server through websockets. And I have an API for Android which gather information to send to the server.
How can I invoke that Android methods which use callbacks and everything from the background isolate?
EDIT
So far in dart I created an Isolate to periodically invoke the poolSong method in background even if the user is using another app or has the screen turned off.
But that gives me the error below...on the github issues they say that I can't send a platform message from a different Isolate unless it's the main. But if I do it from the main isolate, when the user exit the app that isolate will terminate too.
MainDart
class _MyHomePageState extends State<MyHomePage> {
final GlobalKey<ScaffoldState> scaffoldKey = new GlobalKey<ScaffoldState>();
static const platform = const MethodChannel('mainService');
static _poolSong(SendPort sendPort) async {
const oneSec = const Duration(seconds:1);
new Timer.periodic(oneSec, (Timer t) => platform.invokeMethod('poolSong'));
}
#override
void initState() {
super.initState();
ReceivePort receivePort = ReceivePort();
Isolate.spawn(_poolSong, receivePort.sendPort);
}
·
·
·
MainActivityJava
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GeneratedPluginRegistrant.registerWith(this);
new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(
(call, result) -> {
if (call.method.equals("startService"))
startService();
if (call.method.equals("poolSong"))
poolSong();
}
);
}
ERROR
E/flutter (25412): [ERROR:flutter/runtime/dart_isolate.cc(717)] Isolate (765499726) 'main.dart:_poolSong()' exited with an error
E/flutter (25412): [ERROR:flutter/shell/common/shell.cc(186)] Dart Error: Unhandled exception:
E/flutter (25412): error: native function 'Window_sendPlatformMessage' (4 arguments) cannot be found
E/flutter (25412): #0 Window.sendPlatformMessage (dart:ui/window.dart:811:9)
E/flutter (25412): #1 BinaryMessages._sendPlatformMessage (package:flutter/src/services/platform_messages.dart:39:15)
E/flutter (25412): #2 BinaryMessages.send (package:flutter/src/services/platform_messages.dart:87:12)
E/flutter (25412): #3 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:286:49)
E/flutter (25412): <asynchronous suspension>
E/flutter (25412): #4 _MyHomePageState._poolSong.<anonymous closure> (package:musictie/main.dart:37:54)
E/flutter (25412): #5 _Timer._runTimers (dart:isolate/runtime/libtimer_impl.dart:382:19)
E/flutter (25412): #6 _Timer._handleMessage (dart:isolate/runtime/libtimer_impl.dart:416:5)
E/flutter (25412): #7 _RawReceivePortImpl._handleMessage (dart:isolate/runtime/libisolate_patch.dart:171:12)
This error happens when trying to run dart code when the app is in the garbage (app closed), Until now the best way for dealing with background service is to do what you need in native code, and dont try to run anything from dart when app closed.
Since Flutter 3.7 plugins and platform channels can be used from any isolate, not only from the root one.
References:
https://medium.com/flutter/introducing-background-isolate-channels-7a299609cad8
https://github.com/flutter/flutter/issues/13937