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

How to use flutter_blue with flutter_isolate? #13

Closed
vikramkapoor opened this issue Jun 8, 2019 · 3 comments
Closed

How to use flutter_blue with flutter_isolate? #13

vikramkapoor opened this issue Jun 8, 2019 · 3 comments

Comments

@vikramkapoor
Copy link

Thank you for writing this plugin. I am trying to use flutter_blue with this to listen to bluetooth notifications in background. However, I always get state = BluetoothState.unknown from the background isolate when I check flutterBlue.state. The same call gets state = BluetoothState.on from the foreground. Am I using this correctly?

void isolate1(SendPort sendPort) async {

FlutterBlue flutterBlue = FlutterBlue.instance;

/// State
StreamSubscription _stateSubscription;
BluetoothState state = BluetoothState.unknown;

/// Scanning
StreamSubscription _scanSubscription;
Map<DeviceIdentifier, ScanResult> scanResults = new Map();
bool isScanning = true;

/// Device
BluetoothDevice device;
//bool get isConnected => (device != null);
StreamSubscription deviceConnection;
StreamSubscription deviceStateSubscription;
List services = new List();
Map<Guid, StreamSubscription> valueChangedSubscriptions = {};
BluetoothDeviceState deviceState = BluetoothDeviceState.disconnected;

flutterBlue.setUniqueId('FlutterBlue');

// Immediately get the state of FlutterBlue

print ("Get bluetooth state");
flutterBlue.state.then((s) {
state = s;
if (state != BluetoothState.on) {
print("Please turn bluetooth on");
}
else {
print("Bluetooth is on. Starting scan");
_scanSubscription = flutterBlue.scan(
timeout: const Duration(seconds: 30),
withServices: [
new Guid('0000FFE0-0000-1000-8000-00805F9B34FB')
]).listen((scanResult) {
print('localName: ${scanResult.advertisementData.localName}');
print(
'manufacturerData: ${scanResult.advertisementData.manufacturerData}');
print('serviceData: ${scanResult.advertisementData.serviceData}');
scanResults[scanResult.device.id] = scanResult;
//_stopScan();
//_connect(scanResult.device);
},
);
}
});
/*
ReceivePort conPort;
sendPort.send(conPort );
print('Spawning isolate 2');
final isolate = await FlutterIsolate.spawn(isolate2, "hello2");
FlutterStartup.startupReason.then((reason) {
print("Isolate1 $reason");
});*/
int counter = 0;
Timer.periodic(new Duration(seconds: 1), (Timer t) {
counter++;
String msg = 'notification ' + counter.toString();
print('SEND: ' + msg + ' - ');
sendPort.send(msg);
});
Timer.periodic(
Duration(seconds: 1), (timer) => print("Timer Running From Isolate 1"));
}

@vikramkapoor
Copy link
Author

I fixed this issue by creating a custom registrant. Generated registrant has a lot of plugins which were trying to register an Activity from background isolate which led to an error that prevented Flutter_blue registration.

@MichealReed
Copy link

@vikramkapoor mind sharing your updated code?

@vikramkapoor
Copy link
Author

Hi MichaelReed, Sorry I just saw this. Do you still need this?

Here's the code for custom registrant

Custom Registrant

package io.flutter.plugins;

import io.flutter.plugin.common.PluginRegistry;
import com.pauldemarco.flutterblue.FlutterBluePlugin;


/**
 * Generated file. Do not edit.
 */
public final class IsolatePluginRegistrant {
  public static void registerWith(PluginRegistry registry) {
    if (alreadyRegisteredWith(registry)) {
      return;
    }
    FlutterBluePlugin.registerWith(registry.registrarFor("com.pauldemarco.flutterblue.FlutterBluePlugin"));

  }

  private static boolean alreadyRegisteredWith(PluginRegistry registry) {
    final String key = IsolatePluginRegistrant.class.getCanonicalName();
    if (registry.hasPlugin(key)) {
      return true;
    }
    registry.registrarFor(key);
    return false;
  }
}

Invoke custom registrant from MainActivity

package com.rakshak.safeho

import android.content.Intent
import android.os.Bundle
import io.flutter.app.FlutterActivity
import io.flutter.plugins.GeneratedPluginRegistrant
import io.flutter.plugins.IsolatePluginRegistrant
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import com.rmawatson.flutterisolate.FlutterIsolatePlugin
import com.google.android.gms.actions.NoteIntents

class MainActivity(): FlutterActivity() {
     var savedNote:String? = null

    override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    FlutterIsolatePlugin.setCustomIsolateRegistrant(IsolatePluginRegistrant::class.java)
    GeneratedPluginRegistrant.registerWith(this)
    var intent = getIntent()
    var action = intent.getAction()
    var type = intent.getType()

    if (NoteIntents.ACTION_CREATE_NOTE.equals(action) && type != null) {
      if ("text/plain".equals(type)) {
        savedNote = intent.getStringExtra(Intent.EXTRA_TEXT)
      }
  }
      MethodChannel(getFlutterView(), "app.channel.shared.data").setMethodCallHandler { call, result ->
          if (call.method == "getSavedNote") {
              result.success(savedNote)
              savedNote = null
          }
      }
  }
}

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

2 participants